Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript字符串。替换不起作用?_Javascript_Replace_Split - Fatal编程技术网

Javascript字符串。替换不起作用?

Javascript字符串。替换不起作用?,javascript,replace,split,Javascript,Replace,Split,我目前正在尝试为我正在创建的网站创建一个导航系统。我花了几个小时想弄明白,但我不明白为什么它不起作用 我试图用变量文件名替换所有出现的“index.html” function changeSideNav(filenames) { var urlarray = window.location.href.split("?"); var url = urlarray[0]; alert(url); // This returns "http://localhost/xx

我目前正在尝试为我正在创建的网站创建一个导航系统。我花了几个小时想弄明白,但我不明白为什么它不起作用 我试图用变量文件名替换所有出现的“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“

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

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

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

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

来自:

小数点匹配任何单个字符 除新行以外的字符 性格所以,比如说 把“猫吃蛾子”串在绳子上 正则表达式/.t/gi将匹配 字母“at”在“cat”中,“at”在“in”中 “吃”和“吃”在“蛾”中,但不是 “the”的首字母“T”

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

url.replace(/index\.html/gi,filenames)
发件人:

小数点匹配任何单个字符 除新行以外的字符 性格所以,比如说 把“猫吃蛾子”串在绳子上 正则表达式/.t/gi将匹配 字母“at”在“cat”中,“at”在“in”中 “吃”和“吃”在“蛾”中,但不是 “the”的首字母“T”

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

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

不确定这是否是你的问题。但我在这件事上坚持了好一个小时

在这里:
str.replace(“s1”、“s2”)
对str没有任何作用

您需要执行以下操作:
str=str.replace(“s1”、“s2”)

请注意,LHS将显式捕获替换的结果


希望有帮助:)

不确定这是否是你的问题。但我在这件事上坚持了好一个小时

在这里:
str.replace(“s1”、“s2”)
对str没有任何作用

您需要执行以下操作:
str=str.replace(“s1”、“s2”)

请注意,LHS将显式捕获替换的结果


希望它有帮助:)

为什么不简单地
url.replace(“/index.html”,文件名)
?这段代码实际上工作得很好。如果我是你,我会发出
警报(文件名)
以确保你知道发生的一切。为什么不简单地
url.replace(“/index.html”,文件名)
?该代码实际上运行得很好。如果我是你,我会发出一个
警报(文件名)
,以确保你知道正在发生的一切。但实际上,“.”与“index.html”中的“.”匹配得很好。@Pointy,是的。。。如果你转义它。如果你不转义它,它也会匹配一个“.”,因为“.”匹配任何字符-包括“.”。但是“.”实际上会匹配“index.html”中的“.”很好。@Pointy,是的。。。如果你转义它。如果你不转义它,它也将匹配一个“.”,因为“.”匹配任何字符-包括“.”。