有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?


当前回答

使用jQuery,您可以使用

$('#elementID').text()

其他回答

我想分享一下Shog9批准答案的编辑版本。


正如Mike Samuel在评论中指出的那样,该函数可以执行内联javascript代码。但Shog9说“让浏览器为你做……”是对的

所以…这里是我的编辑版本,使用DOMParser:

function strip(html){
   let doc = new DOMParser().parseFromString(html, 'text/html');
   return doc.body.textContent || "";
}

这里是测试内联javascript的代码:

strip("<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>")

此外,它不会在解析时请求资源(如图像)

strip("Just text <img src='https://assets.rbl.ms/4155638/980x.jpg'>")

使用jQuery,您可以使用

$('#elementID').text()

我认为最简单的方法就是像上面提到的那样使用正则表达式。虽然没有理由使用一堆。尝试:

stringWithHTML = stringWithHTML.replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, "");

来自CSS技巧:

https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/

常量原始字符串=`<div><p>嘿,这是什么东西</p></div>`;conststripedString=originalString.replace(/(<([^>]+)>)/gi,“”);console.log(strippedString);

要获得更简单的解决方案,请尝试此=>https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/

var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");