DanteDiaze
DanteDiaze

Reputation: 128

Javascript : Replace url between href tag

I am trying to replace urls between the href tag but unfortunately i don't know the javascript equivalent of

(?<=href=(\"|'))[^\"']+(?=(\"|'))

Javascript is missing the positive look behind.

Any idea how i can achieve this please ? Thank you !

Upvotes: 1

Views: 356

Answers (2)

tevemadar
tevemadar

Reputation: 13225

It is just an attribute on the anchor element:

function magic(){
    var a=document.getElementById("anchor");
    a.href="http://www.stackoverflow.com";
}
<a href="#" id="anchor">Trallala</a>
<button onclick="magic()">Pushme</button>

EDIT: Apparently links are not very welcome in these code snippets, but you can check the change via hovering, and you can also open the link in a new window/tab

Upvotes: 1

Duncan Thacker
Duncan Thacker

Reputation: 5188

In general, trying to modify HTML with regular expressions is really difficult, dangerous, and hard to maintain. You'll have a much better time using a HTML manipulation library like jQuery:

<a id='myLink' href='http://fish.com'></a>

var $link= $("'#myLink");
$link.attr("href", "http://melons.com');

Upvotes: 0

Related Questions