如何使用JS删除所有尖括号和内部的一切?

时间:2017-12-02 20:52:08

标签: javascript

我有一串HTML元素,

let test = `<figure><img alt="" src="some_image.jpg"><figcaption>I think DC is better than Marvel <span class="whatever">...`

我需要移除每一个<...>,因此它会变成test = "I think DC is better than Marvel..."

我最接近的是:

var str = "<hello> Test </hello>"
str.replace(/<[^>]*/g, ""); //=> "> Test >"
str.replace(/<*>*/g, ""); //=> "hello Test /hello"
但是,不完全是这样。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

将HTML添加为新元素的innerHTML,然后提取textContent

let test = `<figure><img alt="" src="some_image.jpg"><figcaption>I think DC is better than Marvel <span class="whatever">`

const el = document.createElement('div');
el.innerHTML = test;
const txt = el.textContent;
console.log(txt);