在 JavaScript 中从内容的开头和结尾删除<p><br/></p>标记



我正在寻找一个javascript正则表达式,通过它我可以从我的内容中删除<p><br><p>标签。

例如:

下面是我的内容

<p><br></p>
<p>function removes whitespace or other predefined characters from the right side of a string.</p>
<p><br></p>
<p><br/><p>

我正在寻找这个

<p>function removes whitespace or other predefined characters from the right side of a string.</p>

我正在使用此代码,但它不起作用

function rtrim(str) {
if(!str) return str;
return str.replace(/s+$/g, '');
}
console.log(rtrim(string));

您希望删除 HTML 换行符<br/>及其周围的段落元素<p>而不是空格,这是您使用当前正则表达式执行的。

\s+匹配任何空格字符(等于 [\r\t\f\v ](

这应该是您情况下的正确正则表达式<p><br[/]?><[/]?p>

function rtrim(str) {
if(!str) return str;
return str.replace(/<p><br[/]?><[/]?p>/g, '');
}
console.log(rtrim("<p><br></p><p>function removes whitespace or other predefined characters from the right side of a string.</p><p><br></p><p><br/><p>"));

我使用<br[/]?>来确保带正斜杠和不带正斜杠的换行符都匹配。

而不是替换<p><br></p>,只能提取<p>some text</p>

例如,如下所示,

let a = "<p><br></p><p>function removes whitespace or other predefined characters from the right side of a string.</p><p><br></p><p><br/><p>";
a = /(<p>[^<>].*[^<>]</p>)/g.exec(a)[0];
console.log(a); // "<p>function removes whitespace or other predefined characters from the right side of a string.</p>"

如果你特别需要一个正则表达式,我会建议Red发布的答案。

如果您不需要使用 RegExp,您可以按行拆分并过滤该字符串,然后再次连接它,
尽管此示例仅在它们被n分隔时才有效

function rtrim(str) {
if(!str) return str;
return str
.split('n')
.filter((s) => s === '<p><br></p>')
.join('n');
}

最新更新