开发者

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开发者_StackOverflow社区 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


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");
    }
});


Are these always in links? If so:

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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜