1

I have an regex to find the part of a <a href=""> within the innerHTML of a div.

      var b = this.innerHTML.match(/href="([^\'\"]+)/g);
      var c = b[0].split('#')[1];
      window.location.assign('#'+c);

and would like to get rid of the second line, the .split function. Is there a way to do this? Ideally, I'd like to keep the hashtag before the div, too:

The hrefs are allways like this (only the number is subject to change):

href="#div46" 
href="#div47"
...
baao
  • 71,625
  • 17
  • 143
  • 203

3 Answers3

3

You can use:

var b = this.innerHTML.match(/href=(['"])(.+?)\1/);
window.location.assign( b[2] ); // #div46
  • Remove g flag to get all matched groups in resulting array.
anubhava
  • 761,203
  • 64
  • 569
  • 643
1
var val = $("a").attr("href");
var myString = val.substr(val.indexOf("#") + 1)
alert(myString);

Try this

user8025
  • 99
  • 1
  • 9
1

You don't need a regular expression for that:

// 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. 
axel.michel
  • 5,764
  • 1
  • 15
  • 25