开发者

Javascript replacing new line character

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜