Javascript String.Replace 不起作用?
我目前正在尝试为我正在创建的网站创建一个导航系统。我花了几个小时试图解决这个问题,但我不明白为什么它不起作用 我试图用变量文件名替换所有出现的“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”。
I'm currently trying to create a navigation system for a website I'm creating. I spent hours trying to figure this out, but i dont understand why its not working
I'm trying to replace all occurrences of "index.html" with the variable filenames.
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;
}
Edit:
i find this to be strange:
if i try to replace "/index.html" instead of "index.html", it removes the "/" from the output so i get "http://localhost/xxxindex.html/newpage.html".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定这是否是您的问题。但我在这件事上坚持了一个小时。
这是:
str.replace("s1", "s2")
不会对 str 执行任何操作。你需要做:
str=str.replace("s1", "s2");
请注意 LHS 显式捕获替换结果。
希望它有帮助:)
Not sure if this was your prob. But I was stuck on this for a good hour.
Here it is:
str.replace("s1", "s2")
does NOT do anything to the str.You need to do:
str=str.replace("s1", "s2");
Notice the LHS to explicitly capture the result of the replacement.
Hope it helps :)
您将字符串指定为正则表达式。尝试指定一个子字符串作为要替换()的第一个参数,如下所示:
参见String.replace 的文档
You're specifying a string as a regex. Try specifying a substring as the 1st param to replace(), like so:
See docs for String.replace
来自http://www.devguru.com/technologies/ecmascript/quickref/regexp_special_characters。 html:
所以你必须逃避这个时期:
From http://www.devguru.com/technologies/ecmascript/quickref/regexp_special_characters.html:
So you have to escape the period: