如果满足条件,我需要在HTML上替换特定网址的所有实例。我怎么能只使用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") )
})
}
这不起作用,因为显然网址中的“/”搞乱了正则表达式,我不确定写它的正确方法是什么,但也因为它是jQuery而我不想要将jQuery添加到整个站点只是为了运行它。
答案 0 :(得分:0)
你需要逃避这个正斜杠字符
"http://www.homepage.com".replace(/http:\/\/www.homepage.com/g, "http://www.homepage.com/home")
答案 1 :(得分:0)
可能是这样的:
function replace(element, oldurl, newurl){
element.innerHTML.split(oldurl).join(newurl);
}
并使用它:
replace(document.getElementById("container"), "www.old.com", "new.com");