Jeremy Nelson
Jeremy Nelson

Reputation: 286

How to get href of string in Javascript

a 3rd party tool I'm using builds an anchor tag like so..

"<a href="http://DevNode/Lists/Publications.aspx#/publication/123">http://DevNode/Lists/Publications.aspx#/publication/123</a>"

I need to isolate the href so I can trim it. Currently my pattern of

reg = /^(<a\shref=")? http:\/\/DevNode\/Lists\/Publications.aspx#\/publication\/(\d+)/i {lastIndex: 0} 

will fail to match if the href has a leading space like this

"<a href=" http://DevNode/Lists/Publications.aspx#/publication/123"> http://DevNode/Lists/Publications.aspx#/publication/123</a>"

Please help

Upvotes: 0

Views: 3505

Answers (4)

Dan Nagle
Dan Nagle

Reputation: 5425

Keep it simple:

var ahref = '<a href="http://DevNode/Lists/Publications.aspx#/publication/123">http://DevNode/Lists/Publications.aspx#/publication/123</a>';
var href = ahref.split('"')[1];

Upvotes: 1

JorgeObregon
JorgeObregon

Reputation: 3310

An easy/fast answer is using jQuery, building the tag, and looking for the href attribute.

$('<a href="http://DevNode/Lists/Publications.aspx#/publication/123">http://DevNode/Lists/Publications.aspx#/publication/123</a>')
.attr('href')

I'll try to get you the RegExp in a bit. Hang on tight...

And as promissed... here's the RegExp

var text = '<a href="http://DevNode/Lists/Publications.aspx#/publication/123">http://DevNode/Lists/Publications.aspx#/publication/123</a>';
console.log(text.match(/<a\s+(?:[^>]*?\s+)?href="([^"]*)"/)[1])

Upvotes: 0

Simon
Simon

Reputation: 2423

You may want to use the * quantifier that says "any number of times including zero" combined to the \s it will match spaces, newlines or else.

So use \s+ where a space is required but there might be more than one

And use \s* where a space is optional but there might be some

reg = /^(<a\s+href=")?\s*http:\/\/DevNode\/Lists\/Publications.aspx#\/publication\/(\d+)/i

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074038

If you're doing this on a browser the simplest way is to let the browser figure it out:

var div = document.createElement("div");
div.innerHTML = yourString;
var href = div.querySelector("a").href;

This also has the advantage of resolving it if it's a relative URL. If you don't want that, use getAttribute instead:

var href = div.querySelector("a").getAttribute("href");

Note that if you use getAttribute, if the attribute has a leading space, the leading space will be in the result; String#trim could be useful if you want to get rid of it.

Upvotes: 7

Related Questions