Javascript替换新行字符 [英] Javascript replacing new line character

查看:68
本文介绍了Javascript替换新行字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我发疯,我的格式是字符串:

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>

以下代码:

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

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

我要做的是删除< br />> ;并用< br />替换它我不能简单地替换所有出现的>因为它们可能包含在行的其他位置,所以我只想在开始时删除它们。我已经尝试了转义字符并硬编码正则表达式以显式删除新行,而不是将它们包含在函数调用中。任何帮助将不胜感激。

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.

推荐答案

如果您的目标只是删除所有> s在行的开头,这很容易做到:

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"), "");

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

m 标志意味着多行所以 ^ $ 将匹配行的开头和结尾,而不仅仅是字符串的开头和结尾。请参阅 RegExp对象

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.

编辑:值得一提的是,你应该可能赞成使用 RegExp 对象而不是第二张表单(正则表达式字面)。请参阅 / regex / Literals是否总是RegExp对象?为什么在Javascript中使用全局标志的RegExp会给出错误的结果?

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?.

此外,在多次使用的正则表达式文字中如何处理全局标志存在浏览器差异。最好避免它,并明确使用 RegExp 对象。

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.

这篇关于Javascript替换新行字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆