在JavaScript中将多个\ n替换为1 [英] Replace multiple \n with 1 in JavaScript
问题描述
如何只用一个替换多个 \ n
?因此,如果用户输入
How do I replace multiple \n
's with just one? So if a user enters
blah
blahdy blah
blah blah
我希望它最终看起来像。
I want it to end up looking like.
blah
blahdy blah
blah blah
我知道我可以使用while()循环,但宁愿使用正则表达式,因为我认为它更有效。
I know I could loop through with a while() but would rather use a regular expression, since I believe it's more efficient.
推荐答案
这对我有用:
string = string.replace(/\n+/g, '\n');
正如其他人所说的那样,它取代了连续一次或更多的每次出现换行符( \ n +
)只有一个。
As others have said, it replaces each occurrence of one or more consecutive newline characters (\n+
) with just one.
g
影响全局替换,意味着它替换字符串中的所有匹配而不是第一个匹配。
The g
effects a "global" replace, meaning it replaces all matches in the string rather than just the first one.
编辑:如果您还想考虑其他操作系统的行结束样式(例如, \\\
),您可以执行多步替换:
Edit: If you want to take into account other operating systems' line ending styles as well (e.g., \r\n
), you could do a multi-step replace:
string = string.replace(/(\r\n)+/g, '\r\n') // for Windows
.replace(/\r+/g, '\r') // for Mac OS 9 and prior
.replace(/\n+/g, '\n'); // for everything else
OR (感谢Renesis :
string = string.replace(/(\r\n|\r|\n)+/g, '$1');
如果你事先知道你正在处理什么样的文本,上面的内容可能有点过头了它带来了明显的性能成本。
If you know in advance what sort of text you're dealing with, the above is probably overkill as it carries am obvious performance cost.
这篇关于在JavaScript中将多个\ n替换为1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!