使用正则表达式提取元标签

3
我需要从一个字符串中提取meta标签,为此我使用\<meta[\s\S]*?\>,但是我希望在提取时忽略拥有ignore(或someIgnore)属性的meta标签。 <meta property="position" content="1" someIgnore ignore="metaextract"/>这是我的示例函数。

function parseMetas(locals) {
    var str = locals.body, regex = /\<meta[\s\S]*?\>/g;
    if (regex.test(str)) {
        locals.body = str.replace(regex, '');
        locals.meta = str.match(regex).join('\n');
    }
}

1个回答

1
你可以在正则表达式中使用 negative lookahead
function parseMetas(locals) {
    var str = locals.body, 
    let regex = /<meta(?!.*?(ignore|someIgnore))[\s\S]*?\/?>/g;
    if (regex.test(str)) {
        locals.body = str.replace(regex, '');
        locals.meta = str.match(regex).join('\n');
    }
}

演示:

let regex = /<meta(?!.*(ignore|someIgnore))[\s\S]*?\/>/g;
let input = `
    <meta property="position" content="1" someIgnore ignore="metaextract"/>,
    <meta property="position" content="1" ignore="metaextract"/>,
    <meta property="position" content="1"/>,
    <meta property="position" content="1" someIgnore />,
    <meta name="description" content="type_your_description_here"/>,
    <meta charset="utf-8"/>'
`;


console.log(input.match(regex));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接