[英]javascript: extract parts of a string (regex)
The question is simple, assume the following string: 问题很简单,假设使用以下字符串:
var str = '<a href="aaaa">aaaaa</a><a href="bb">b\'s</a>'
How do you extract the value of href. 您如何提取href的值。 I would think something like
我会想像
var arr = str.match(/(?:href=")(\w+)/g) ;
--> ["href="aaaa", "href="bb"]
Of course I want 我当然要
["aaaa", "bb"]
Withoug the /g it get close, but it only matches "aaaa". 与/ g失去联系,但仅匹配“ aaaa”。 Any suggestions how to fix this ?
任何建议如何解决这个问题?
Thanks! 谢谢!
Because Javascript doesn't have lookbehind, this may be what you want. 因为Javascript没有后顾之忧,所以这可能就是您想要的。 Naturally there will be more elegant solutions:
自然会有更多的优雅的解决方案:
input.match(/<[^href|/]*(href[\s]*=[\s]*")([^"]+)(?=">)/g).map(
function(x){return x.split('href')[1].replace(/[^"]+"(.*)/,'$1');
})
Additionally, you may be better off getting a HTML parsing plugin. 此外,你可能会更好得到一个HTML解析插件。 And extracting the properties you need using that.
并使用该属性提取所需的属性。
Cheers. 干杯。
DOM parsing with JS is so easy. 用JS进行DOM解析非常简单。
var str = '<a href="aaaa">aaaaa</a><a href="bb">b\'s</a>',
help = document.createElement('div');
helper.innerHTML = str;
Array.prototype.forEach.call(help.querySelectorAll("a[href]"), function (elem) {
console.log(elem.getAttribute('href'));
});
http://jsfiddle.net/ExplosionPIlls/gtdFh/ http://jsfiddle.net/ExplosionPIlls/gtdFh/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.