Reputation: 73241
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"
...
Upvotes: 1
Views: 69
Reputation: 5764
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.
Upvotes: 1
Reputation: 99
var val = $("a").attr("href");
var myString = val.substr(val.indexOf("#") + 1)
alert(myString);
Upvotes: 1
Reputation: 785156
You can use:
var b = this.innerHTML.match(/href=(['"])(.+?)\1/);
window.location.assign( b[2] ); // #div46
g
flag to get all matched groups in resulting array.Upvotes: 3