如何使用Javascript替换页面上url的所有实例?

如何使用Javascript替换页面上url的所有实例?,javascript,Javascript,如果满足条件,我需要替换HTML上特定url的所有实例。我怎么能只用Javascript而不是jQuery来实现呢 我一直在尝试这样的事情: if () { $("#container").contents().each(function () { if (this.nodeType === 3) this.nodeValue = $.trim($(this).text()).replace(/http://www.homepage.com/g, "http://www.homepag

如果满足条件,我需要替换HTML上特定url的所有实例。我怎么能只用Javascript而不是jQuery来实现呢

我一直在尝试这样的事情:

if () {

$("#container").contents().each(function () {
    if (this.nodeType === 3) this.nodeValue = $.trim($(this).text()).replace(/http://www.homepage.com/g, "http://www.homepage.com/home")
    if (this.nodeType === 1) $(this).html( $(this).html().replace(/http://www.homepage.com/g, "http://www.homepage.com/home") )
})

}

这不起作用,因为很明显url中的“/”弄乱了正则表达式,我不确定正确的编写方法是什么,但也因为它是jQuery,我不想为了运行它而将jQuery添加到整个站点。

您需要转义这个正斜杠字符

"http://www.homepage.com".replace(/http:\/\/www.homepage.com/g, "http://www.homepage.com/home")
可能是这样的:

function replace(element, oldurl, newurl){
   element.innerHTML.split(oldurl).join(newurl);
}
并使用它:

replace(document.getElementById("container"), "www.old.com", "new.com");