Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何改进这个正则表达式_Javascript_Regex - Fatal编程技术网

Javascript 如何改进这个正则表达式

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

我使用正则表达式在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 = 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我不明白@比芬:我怎样才能得到结果呢?