Jquery查找并替换部分URL?

时间:2011-07-07 20:12:32

标签: jquery regex replace

我正在尝试在整个页面中进行查找和替换,并向包含某些指定文本的任何URL添加一些参数。 (我说的是硬编码的内联href URL)

所以,例如,我想替换这个的任何实例:

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

使用

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

我尝试了一些我发现的替换功能,但是我无法使用字符串中的正斜杠。

对此有任何帮助将不胜感激。感谢

4 个答案:

答案 0 :(得分:2)

只需简单地添加到字符串上,您就不需要替换任何内容。

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

或者如果您只想替换一个href,您可以执行以下操作:

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

这包括带有查询字符串的url:

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

答案 1 :(得分:0)

检查我使用替换创建的此示例,它可以正常工作。

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

答案 2 :(得分:0)

这些是否始终在链接中?如果是这样的话:

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

答案 3 :(得分:0)

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