仅获取HTML属性值 - 正则表达式

时间:2018-01-28 09:09:38

标签: javascript html regex

我确实想要检查两方征收 - [工作]

var str = '<a href="url"></a><a href="url2"></a><a href="url3"></a>';
console.log(str.match(/(?!href=")[^"]+?(?=")/g))
>> (6) ["<a href=", "url", "></a><a href=", "url2", "></a><a href=", "url3"]

这个正则表达式检查两侧到期然后在匹配字符串中提取。

但是在html中它不起作用 [not working]

Negative lookarounds

我尝试(?!href=")使用 Positive lookarounds (?=")使用 href=" 来仅匹配其值属性&lt; a url " for&gt;但它会返回更多属性。

1 个答案:

答案 0 :(得分:1)

这里有一些相同的问题:

您可以为示例数据执行的操作是捕获捕获组中双引号href =“([^”] +)之间的内容并循环显示结果:

var str = '<a href="example.com"></a><a href="example2.com"></a><a href="example3.com"></a>';
var pattern = /href="([^"]+)/g;
var match = pattern.exec(str);
while (match != null) {
    console.log(match[1]);
    match = pattern.exec(str);
}

  

不要忘记在正则表达式上放置global标志。 / href =“([^”] +)/ g &lt; -this little g flag

查看更多:Regex check both side of match but not include in match string