levi
levi

Reputation: 25161

Jquery find and replace part of a URL?<a

I am trying to do a find and replace throughout an entire page, and add some parameters to any URLs that contain some specified text. (i am speaking about hardcoded inline a href URLs)

So for example, I want to replace any instances of this:

<a href ="http://localhost/wordpress/">Link</a>

With

<a href ="http://localhost/wordpress/?demo_mobile_site">Link</a>

I tried some replace function I found, but I cant get it to work with the forward slashes in the string.

Any help on this would be appreciated. Thanks

Upvotes: 0

Views: 7848

Answers (4)

locrizak
locrizak

Reputation: 12279

You don't need t replace anything just simple add onto a string.

$('a').each(function(){
    var _href = $(this).attr('href');
    $(this).attr('href', _href + (_href.charAt(_href.length-1) == '/' ?  "? demo_mobile_site" : "/?demo_mobile_site");
});

or if you just want to replace the one href you can do something like this:

$('a[href^="http://localhost/wordpress"]').each(function(){
    var _href = $(this).attr('href');
    $(this).attr('href', (_href.charAt(_href.length-1) == '/' ? _href + "?demo_mobile_site" : "/?demo_mobile_site");
});

This including url's with query strings:

$('a').each(function(){
    var _href = $(this).attr('href');

    if ( _href.indexOf('?') >= 0 ){
        $(this).attr('href', _href + "&demo_mobile_site=");
    } else if ( _href.charAt(_href.length-1) == '/' ) {
        $(this).attr('href', _href + "?demo_mobile_site");
    } else {
        $(this).attr('href', _href + "/?demo_mobile_site");
    }
});

Upvotes: 2

Tak
Tak

Reputation: 11732

$('a[href="http://localhost/wordpress/"]').each(function(){
    var newhref = $(this).attr('href') + '?mobile_site';
    $(this).attr('href', newhref);
});

Upvotes: 0

Pit Digger
Pit Digger

Reputation: 9800

Check this sample I created with replace it works fine.

http://jsfiddle.net/zRaUp/

 var value ="This is some text . http://localhost/wordpress/ Some text after ";
    var source= "http://localhost/wordpress/";
     var dest = "http://localhost/wordpress/?demo_mobile_site";
    alert(value);
     value= value.replace(source,dest);
    alert(value);

Upvotes: 0

Marc
Marc

Reputation: 3902

Are these always in links? If so:

$('a[href="http://localhost/wordpress/"]').attr('href', 'http://localhost/wordpress/?demo_mobile_site');

Upvotes: 0

Related Questions