[英]How to remove line breaks from a string, but only between certain tags?
我已经找到了如何从字符串中删除所有换行符,但是我没有HTML标记,而是简单的字符串。 我的目标是仅删除<p>
标记内的字符串部分的所有换行符。
示例字符串:
var str = `<h1>Headline do not touch me, nor the line break</h1>
<p>This is
a test string, please
put me on one line.</p>`;
应该变成:
var str = `<h1>Headline do not touch me, nor the line break</h1>
<p>This is a test string, please put me on one line.</p>`;
实现此目标的JS代码/正则表达式是什么?
注意:在生产中我的字符串中有几个p标签。
我在另一个网站上找到了此文件,但无法相应地对其进行修改: str=str.replace(/(<[^>]+>)/g,function(w){return w.replace(/(\\r\\n|[\\r\\n])/g,' ')});
您可以使用两个正则表达式来替换标签中的新行,而使用另一个来删除标签之间的新行
<[^>]+>[\\s\\S]+?<\\/[^>]+>
--> to remove new line inside tags
(<\\/[^>]+>)\\n+(?=<[^>]+>)
--> to remove new line between tags
let str = `<h1>Headline One Do not touch</h1> <p> This is a test string, please put me on one line. </p> <p> some text </p> ` let output = str.replace(/<[^>]+>[\\s\\S]+?<\\/[^>]+>/g, m => m.replace(/\\n+/g, '')) let final = output.replace(/(<\\/[^>]+>)\\n+(?=<[^>]+>)/g,'$1\\n') console.log(final)
如果您的字符串中只有一个p标签,则下面的代码有效。
var str = `<h1>Headline do not touch me, nor the line break</h1>
<p>
This is
a test string, please
put me on one line.
</p>`;
var str = str.substring(0, str.indexOf('<p>')) + str.slice(str.indexOf('<p>'), str.indexOf('</p>')).replace(/(\r\n|[\r\n])/g,' ') + str.substring(str.indexOf('</p>'), str.length);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.