如何在全局范围内替换URL

时间:2017-03-03 05:37:05

标签: javascript jquery

首次出现时工作正常,但我发现多个匹配的网址不会被替换。

如果我正在使用全局标记' g '第一次出现也不起作用。

我需要更改所有匹配的网址。

HTML:

 <p id="demo">
    Welcome to <a href="http://google.com?sdfsdf">US </a> and s sdfsdfsdf sdfsdf<a href="http://google.com?sdfsdf">US </a>dfsdfsdfsd<a href="http://google.com?sdfsdf">US </a>sfsdfsdfsdfsdf<a href="http://live.com?dfgdfgdfg?dfgdfg=2016">US </a>
    </p>

JS:

var str = document.getElementById("demo").innerHTML; 
var res = str.replace("http://google.com?sdfsdf", "sample link url");
document.getElementById("demo").innerHTML = res;

2 个答案:

答案 0 :(得分:1)

我们可以使用jQuery attribute contains selector选择包含您要查找的href值的所有链接

var searchString = 'http://google.com?sdfsdf'; // specify the search value
var replaceString = 'Replace with me'; // specify the value to replace found strings with
// for each anchor tag with an href containing the search string
$("a[href*='" + searchString + "']").each(function(){
    // replace its current href with a the search string replaced
    $(this).attr('href', $(this).attr('href').replace(searchString, replaceString));
});

注意:如果您实际上是在尝试替换匹配元素的整个网址,则可以省去.replace函数,如下所示:

$(this).attr('href', replaceString);

答案 1 :(得分:0)

检查一下。这可能有效https://jsfiddle.net/sfhmvrdo/

  <a href="http://google.com">google</a>
<a href="http://google.com">more google</a>
<a href="http://stackoverflow.com">fb</a>
<button>
click here
</button>

这是你需要的jquery。

$('button').click(function(){

 change_href();
});

function change_href(){
 $("a").each(function() {
 if($(this).attr('href')=="http://google.com"){
 $(this).attr('href','http://facebook.com');
 }
 });
}