The fast & forgiving HTML/XML parser.(一个快速宽松的HTML/XML解析器)
文档
- npm https://www.npmjs.com/package/htmlparser2
- github https://github.com/fb55/htmlparser2
- wiki https://github.com/fb55/htmlparser2/wiki/Parser-options
安装
npm install htmlparser2
使用示例
import { Parser } from "htmlparser2"; /** * 解析出所有类名 * @param {String} html * @returns {Array} */ function extractClassList(html) { let classList = []; const parser = new Parser({ onattribute(name, value) { if (name == "class") { classList.push(value); } }, }); parser.write(html); parser.end(); return classList; } const html = '<div class="box"><div class="box__header" style="color:#333;"></div><div class="box__body"></div></div>'; let classList = extractClassList(html); console.log(classList); // [ 'box', 'box__header', 'box__body' ]
参考