首页 > 解决方案 > 移除


在 JavaScript 中从内容的开始和结束标记

问题描述

我正在寻找一个 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));

标签: javascript

解决方案


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

\s+匹配任何空白字符(等于 [\r\n\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[\/]?>确保带和不带正斜杠的换行符都匹配。


推荐阅读