如何删除字符串中的换行符,但仅在某些标签之间?

时间:2019-07-16 11:20:50

标签: javascript regex

我已经找到了How to remove all line breaks from a string,但是我没有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,' ')});

2 个答案:

答案 0 :(得分:0)

您可以使用两个正则表达式来替换标签中的新行,而使用另一个来删除标签之间的新行

  1. <[^>]+>[\s\S]+?<\/[^>]+> --> to remove new line inside tags

enter image description here

  1. (<\/[^>]+>)\n+(?=<[^>]+>) --> to remove new line between tags

enter image description here

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)

答案 1 :(得分:0)

如果您的字符串中只有一个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);
相关问题