JavaScript来提取字符串里面HTML内容中所有id的值

88 阅读1分钟

下面是JavaScript代码示例:

const htmlContent = '<h1 id="标题1">一、标题1</h1>\n<p>内容1</p>\n<p>内容1</p>\n<p>内容1</h1>\n<p>内容1</p>\n<p>内容1</p>\n<p>内容1</p>\n<h1 id="标题2"><br />二、标题2</h1>\n<p>内容2</p>\n<p>内容2</p>\n<p>内容2</p>\n<p>内容2</p>\n<p>内容2</p>\n<p>内容2</p>\n<p>内容2</p>\n<p>内容2</p>\n<h1 id="标题3"><br />三、标题3</h1>\n<p>内容3</p>\n<p>内容3</p>\n<p>内容3</p>\n<p>内容3</p>\n<p>内容3</p>\n<p>内容3</p>\n<p>内容3</p>\n<p>内容3</p>\n<p>&nbsp;</p>\n<p>&nbsp;</p>'; // 替换为实际的HTML内容

// 使用match()函数和正则表达式/id="([^"]*)"/g来从HTML内容中提取所有的id值,这个正则表达式会匹配所有形式为id="XXXX"的字符串,其中XXXX是我们要提取的id值
const ids = htmlContent.match(/id="([^"]*)"/g).map(id => id.substring(4, id.length - 1));

// 输出所有的id值
console.log(ids);

运行的结果:

f45a05733d194df9a2cc56b3bf4a8ba9.png