views:

358

answers:

1

This is driving me crazy, I have a string in the format:

<br />
twice<br />
imap Test wrote:<div class="nestedMessage1"><br />
> nested<br />
><br />
> [email protected] wrote:<div class="nestedMessage2"><br />
>> test<br />
>><br />
>> -- <br />
>> Message sent via AHEM.<br />
>>   </div><br />
><br /><br /></div>

And the following code:

string = string.replace(/\n/g, "");
string = replaceAll(string, "<br />>", "<br />");

function replaceAll(string, replaceString, replaceWith)
{
  return string.replace(new RegExp(replaceString, 'g'),replaceWith);
}

What I am attempting to do is remove the <br />> and replace it with just the <br /> I can't simply replace all occurrences of > as they may be contained elsewhere in the line, so I only want to remove them at the start. I have tried escape characters and have hardcoded the regular expression to remove the new lines explicitly instead of including them in the function call. Any help would be appreciated.

+5  A: 

If your goal is simply to remove all the >s at the beginning of the lines, that's easy to do:

var out = in.replace(new RegExp("^>+", "mg"), "");

or

var out = in.replace(/^>+/mg, "");

The m flag means multi-line so ^ and $ will match the beginning and end of lines, not just the beginning and end of the string. See RegExp Object.

Edit: It's worth mentioning that you should probably favour using the RegExp object over the second form (regex literal). See Are /regex/ Literals always RegExp Objects? and Why RegExp with global flag in Javascript give wrong results?.

In addition there are browser differences in how the global flag is treated on a regex literal that is used more than once. It's best to avoid it and explicitly use a RegExp object.

cletus
An elegant solution to the problem. Much appreciated.
Gazler
+1 for making regex look fun
Jason Rowe