Mark K
Mark K

Reputation: 591

revise href attribute

So I have a link like this:

<a href="http://thissite.org/thisfolder/21/thispage.php">

What I want to do is revise it but keep part of it eg:

<a href="http://thissite.org/thatfolder/21/thatpage.php">

Can this be done with Jquery or js?

I know I can replace href property with jquery but I need to leave part of the url ("21") and just change the text before and after it.

I was thinking maybe grab the href property, stick it in a variable and take it apart and put it back together somehow.

Any help with this would be largely appreciated.

Upvotes: 0

Views: 92

Answers (2)

SLaks
SLaks

Reputation: 887195

You can call replace in a property setter function:

$('a').attr('href', function(index, old) {
    return old.replace(/thisfolder/i, 'thatfolder');
});

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

A rough way of doing this would be:

// "elem" is the element, for example elem=document.getElementById('link_to_change')
var url = elem.getAttribute("href").split("/");
url.pop();
url.push("thatpage.php");
elem.setAttribute("href",url.join("/"));

Upvotes: 1

Related Questions