简体   繁体   中英

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

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.

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

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]) 

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM