从javascript字符串中删除HTML标记

krr*_*r25 28 javascript jquery

我有这个代码:

var content = "<p>Dear sms,</p><p>This is a test notification for push message from center II.</p>";
Run Code Online (Sandbox Code Playgroud)

我想从上面的字符串中删除所有<p></p>标签.只想显示没有html标签的字符串值,如:

"Dear sms, This is a test notification for push message from center II."
Run Code Online (Sandbox Code Playgroud)

Ble*_*der 63

为什么不让jQuery这样做呢?

var content = "<p>Dear sms,</p><p>This is a test notification for push message from center II.</p>";

var text = $(content).text();
Run Code Online (Sandbox Code Playgroud)

  • 请记住,如果`content`有类似&lt; div&gt;的内容.它将成为运行此代码后的标记 (4认同)

Hum*_*ing 26

这是我的解决方案,

function removeTags(){
    var txt = document.getElementById('myString').value;
    var rex = /(<([^>]+)>)/ig;
    alert(txt.replace(rex , ""));

}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,这是最好的答案,因为它的纯JavaScript和你的正则表达式处理所有的HTML标签 (3认同)

Sam*_*rie 9

使用普通的javascript:

content = content.replace(/(<p>|<\/p>)/g, "");
Run Code Online (Sandbox Code Playgroud)