首次出现时工作正常,但我有多个匹配的 URL 出现,但无法替换。
如果我使用全局标记“g”,第一次出现也不起作用。
我需要更改所有匹配的 URL。
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;
最佳答案
我们可以使用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));
});
注意:如果您实际上尝试替换匹配元素的整个 url,则可以消除对 .replace
函数的需要,如下所示:
$(this).attr('href', replaceString);
关于javascript - 如何替换全局URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42571425/