Javascript 如何改进这个正则表达式
我使用正则表达式在div的innerHTML中查找Javascript 如何改进这个正则表达式,javascript,regex,Javascript,Regex,我使用正则表达式在div的innerHTML中查找部分 var b = this.innerHTML.match(/href="([^\'\"]+)/g); var c = b[0].split('#')[1]; window.location.assign('#'+c); 并希望去掉第二行.split函数。有办法做到这一点吗?理想情况下,我也希望在div之前保留hashtag: HREF始终是这样的(只有数字可能会更改): 您可以使用: var b = t
部分
var b = this.innerHTML.match(/href="([^\'\"]+)/g);
var c = b[0].split('#')[1];
window.location.assign('#'+c);
并希望去掉第二行.split函数。有办法做到这一点吗?理想情况下,我也希望在div之前保留hashtag:
HREF始终是这样的(只有数字可能会更改):
您可以使用:
var b = this.innerHTML.match(/href=(['"])(.+?)\1/);
window.location.assign( b[2] ); // #div46
- 删除
标志以获取结果数组中的所有匹配组g
var b = this.innerHTML.match(/href=(['"])(.+?)\1/);
window.location.assign( b[2] ); // #div46
- 删除
标志以获取结果数组中的所有匹配组g
不需要正则表达式:
// you can extract all fragments of an url like this:
var linkElement = document.createElement('a');
linkElement.href = "http://example.com:3000/pathname/?search=test#hash";
linkElement.protocol; // => "http:"
linkElement.hostname; // => "example.com"
linkElement.port; // => "3000"
linkElement.pathname; // => "/pathname/"
linkElement.search; // => "?search=test"
linkElement.hash; // => "#hash"
linkElement.host; // => "example.com:3000"
// in case you already have a link, you'll don't have to create it - just
// use the element and ask for hash - and you are done.
您不需要正则表达式:
// you can extract all fragments of an url like this:
var linkElement = document.createElement('a');
linkElement.href = "http://example.com:3000/pathname/?search=test#hash";
linkElement.protocol; // => "http:"
linkElement.hostname; // => "example.com"
linkElement.port; // => "3000"
linkElement.pathname; // => "/pathname/"
linkElement.search; // => "?search=test"
linkElement.hash; // => "#hash"
linkElement.host; // => "example.com:3000"
// in case you already have a link, you'll don't have to create it - just
// use the element and ask for hash - and you are done.
@阿努巴瓦这给了我undefined@vks我不明白@比芬:我还能怎样得到结果呢?@anubhava这给了我答案undefined@vks我不明白@比芬:我怎样才能得到结果呢?