简体   繁体   English

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

[英]Removing <p><br/></p> tag from starting and ending of a content in JavaScript

I am looking for a javascript regex through which I could remove the <p><br><p> tag from my content.我正在寻找一个 javascript 正则表达式,通过它我可以从我的内容中删除<p><br><p>标签。

for example:例如:

Below one is my content下面一张是我的内容

<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>

and I am looking for this我正在寻找这个

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

I am using this code but it is not working我正在使用此代码但它不起作用

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

console.log(rtrim(string));

You want to remove the HTML Linebreaks <br/> and its surrounding paragraph element <p> and not whitespaces, which you do with your current regex.您想删除 HTML 换行符<br/>及其周围的段落元素<p>而不是空格,这是您使用当前正则表达式所做的。

\\s+ matches any whitespace character (equal to [\\r\\n\\t\\f\\v ]) \\s+匹配任何空白字符(等于 [\\r\\n\\t\\f\\v ])

This should be the correct regex in your case <p><br[\\/]?><[\\/]?p>在您的情况下,这应该是正确的正则表达式<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>"));

I used <br[\\/]?> to make sure both linebreaks with and without a forward slash will match.我使用<br[\\/]?>来确保带和不带正斜杠的换行符都匹配。

Instead of replacing <p><br></p> , You can extract only <p>some text</p> .而不是替换<p><br></p> ,您可以只提取<p>some text</p>

For example like below,例如像下面这样,

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>"

If you need specifically a RegExp I would suggest the answer posted by Red .如果您特别需要 RegExp,我会建议Red发布的答案。

If you are not required to use a RegExp, you could split by line and filter that string, then join it again,如果您不需要使用正则表达式,您可以按行拆分并过滤该字符串,然后再次加入,
although this example will only work if they are separated by \\n :尽管此示例仅在它们以\\n分隔时才有效

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


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

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