3

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 />
> imap@gazler.com 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.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Gazler
  • 83,029
  • 18
  • 279
  • 245

1 Answers1

9

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.

Community
  • 1
  • 1
cletus
  • 616,129
  • 168
  • 910
  • 942