Jquery查找并替换URL的一部分?<;A.

Jquery查找并替换URL的一部分?<;A.,jquery,regex,replace,Jquery,Regex,Replace,我试图在整个页面中进行查找和替换,并向包含某些指定文本的任何URL添加一些参数。(我指的是硬编码的内联a href URL) 例如,我想替换以下任何实例: <a href ="http://localhost/wordpress/">Link</a> 与 我尝试了一些我找到的替换函数,但是我不能让它与字符串中的前斜杠一起工作 在此方面的任何帮助都将不胜感激。谢谢检查我创建的此示例,替换它工作正常 您不需要替换任何内容,只需简单地添加到字符串中即可 $('a')

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

例如,我想替换以下任何实例:

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


我尝试了一些我找到的替换函数,但是我不能让它与字符串中的前斜杠一起工作


在此方面的任何帮助都将不胜感激。谢谢

检查我创建的此示例,替换它工作正常


您不需要替换任何内容,只需简单地添加到字符串中即可

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

这些都是链接吗?如果是:

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

澄清。。如果javascript检测到访问者在手机上,您希望页面上的硬编码链接被javascript修改吗?或者其他一些可变标准?或者你只是试图永久性地更改链接,而不考虑外部因素?我正在尝试永久性地更改链接,而不考虑任何因素。我在下面的回答中添加了一个链接示例,效果很好。如果你出于某种原因没有结束
/
,这将不起作用更改为
a[href^=”http://localhost/wordpress"]
您指向JSFIDLE的链接不正确。你能添加完整的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");
    }
});
$('a[href="http://localhost/wordpress/"]').attr('href', 'http://localhost/wordpress/?demo_mobile_site');
$('a[href="http://localhost/wordpress/"]').each(function(){
    var newhref = $(this).attr('href') + '?mobile_site';
    $(this).attr('href', newhref);
});