简体   繁体   English

javascript正则表达式,用多行字符串中的单个实例替换多个实例

[英]javascript regex, replace multiple instances with a single one in multiline string

I have a multi-line string in javascript as follows: 我在javascript中有一个多行字符串,如下所示:

"<p> </p>
<p> </p>
<p> </p>
<p> </p>
"

I am trying to remove the extra instances of <p> </p> , so I am trying to use the following regex. 我试图删除<p> </p>的额外实例,所以我试图使用以下正则表达式。

var content = getContent() // This returns the string mentioned above.
content = content.replace(/(<p> <\/p>)+/g, "<p> <\/p>");

But this does not seem to work. 但这似乎不起作用。 Most probably because the string is a multi-line string ? 很可能因为字符串是一个多行字符串? I have tried the above regex with a single line string and it works fine. 我用单行字符串尝试了上面的正则表达式,它工作正常。 After reading a little more documentation about javascript regex, I realized that we need to use the m modifier to deal with multi-line strings. 在阅读了一些关于javascript正则表达式的文档之后,我意识到我们需要使用m修饰符来处理多行字符串。 So I changed the regex to: 所以我把正则表达式改为:

content = content.replace(/(<p> <\/p>)+/gm, "<p> <\/p>"); // note the `m` modifier

But it still does not work. 但它仍然无效。 any clues ? 任何线索?

You should replace all spaces (including new lines) : 您应该替换所有空格(包括新行):

content = content.replace(/(<p>\s*<\/p>\s*)+/g, "<p> <\/p>");

Demonstration 示范

se this replace: 这个替换:

content = content.replace(/(<p> +<\/p>\n*)+/g, "<p> </p>");
/=> <p> </p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM