小而快的 HTML 匹配器
查找 HTML/XML 源代码中指定位置的打开和关闭标签配对 :
import match from '@emmetio/html-matcher';
const content = '<div><a href="http://emmet.io">Example</a></div>';
// Find tag pair at character 35
const tag = match(content, 35);
console.log(tag.name); // Name of matched tag: "a"
console.log(tag.open); // Range of opening tag: [5, 31]
console.log(tag.end); // Range of closing tag: [38, 42]
// List of attributes found in opening tag
console.log(tag.attributes);
默认情况下,匹配者在HTML中工作,这意味着如果找到已知为空的标签名(例如, <img>它不会寻找它即将关闭的部分。 然而,对于XML语法来说,这种行为可能是出乎意料的,因为所有标记都应该是自闭或提供收尾部分. 在这种情况下,你应该通过 xml: true 选项以正确处理 XML 模式 :
import match from '@emmetio/html-matcher';
const content = '<div><img>Caption</img></div>';
const html = match(content, 8);
const xml = match(content, 8, { xml: true });
console.log(html.name); // "img"
console.log(html.open); // [5, 10]
console.log(html.close); // undefined
console.log(xml.name); // "img"
console.log(xml.open); // [5, 10]
console.log(xml.close); // [17, 23]
特殊标签
在HTML中,一些标记有特殊的含义. 例如,a <script> 标签: 在找到关闭前, 其内容应当被完全忽略 </script> 标签。 不过,如果 <script> 标签包含未知 type 属性值,我们应该将其视为一个普通标记。 默认情况下,匹配者会理解 script 财务报告和审定财务报表 style 标记为“ 特殊 ” , 但您可以用 special 选项 :
import match from '@emmetio/html-matcher';
// Treat `<foo-bar>` tag as ”special”: skip its content until `</foo-bar>`. Note that this option overwrites default value with `['script', 'style']` value
match('...', 10, { special: { 'foo-bar': null } });
这个 special 选项是按键为标记名称和值为 type 属性值,如果在标签中存在,则使其具有特殊性。 如果不提供数组,所有带有给定名称的标记将被视为特殊.