我有一些 HTML 内容保存为字符串。
我想遍历该字符串中的每个标题标签并获取其内部文本。
let str = `<h1>topic 1</h1><p>desc of topic 1</p><h1>topic 2</h1><p>desc of topic 2</p>`;
const innerHTMLarr = str.match(/<h1>(.*?)<\/h1>/g).map(x => x);
console.log(innerHTMLarr)Run Code Online (Sandbox Code Playgroud)
数组返回整个标题文本,如何只获取内部文本?
不介意使用 jQuery。
尝试/<\/?h1>/g在里面map()替换所有出现的<h1>和<\h1>,''如下所示:
let str = `<h1>topic 1</h1><p>desc of topic 1</p><h1>topic 2</h1><p>desc of topic 2</p>`;
const innerHTMLarr = str.match(/<h1>(.*?)<\/h1>/g).map(val => {
return val.replace(/<\/?h1>/g,'');
});
console.log(innerHTMLarr)Run Code Online (Sandbox Code Playgroud)