Javascript String.Replace 不起作用

Javascript String.Replace doesnt work?

本文关键字:不起作用 Replace String Javascript      更新时间:2023-09-26

我目前正在尝试为我正在创建的网站创建一个导航系统。我花了几个小时试图弄清楚这一点,但我不明白为什么它不起作用我正在尝试用变量文件名替换所有出现的"index.html"。

function changeSideNav(filenames)
{   
    var urlarray = window.location.href.split("?");
    var url = urlarray[0];
    alert(url); // This returns "http://localhost/xxx/index.html"
    var urlspl = url.replace(/index.html/gi,filenames);
    alert(url.replace(/index.html/i,filenames) +'/'+ filenames); //This returns "http://localhost/xxx/index.html/newpage.html" (if pram was newpage.html).
    //i txpected it to return "http://localhost/xxx//newpage.html"
    //set a new source
    document.getElementById('SideNavIframe').src = urlspl +'/'+ filenames;
}

编辑:我觉得这很奇怪:如果我尝试替换"/index.html"而不是"index.html",它会从输出中删除"/",所以我得到"http://localhost/xxxindex.html/newpage.html"。

不确定这是否是你的问题。但我被困在这件事上整整一个小时。

在这里:
str.replace("s1", "s2")不会对str做任何事情。

您需要做:
str=str.replace("s1", "s2");

请注意 LHS 显式捕获替换结果。

希望对:)有所帮助

您正在指定一个字符串作为正则表达式。 尝试指定一个子字符串作为 replace() 的第一个参数,如下所示:

var url = "http://localhost/xxx/index.html";
url.replace('index.html','changed.html');  // add 'gi' as 3rd param for all occurrences

请参阅字符串的文档.替换

从 http://www.devguru.com/technologies/ecmascript/quickref/regexp_special_characters.html:

小数点匹配任何单个 除换行符外的字符 字符。因此,例如,对于 字符串"猫吃飞蛾" 正则表达式/.t/gi 将匹配 字母"at"在"猫","at"在 "飞蛾"中的"吃"和"ot",但不是 "The"的首字母"T"。

所以你必须逃离这个时期:

url.replace(/index'.html/gi,filenames)