Javascript String.Replace 不起作用
Javascript String.Replace doesnt work?
我目前正在尝试为我正在创建的网站创建一个导航系统。我花了几个小时试图弄清楚这一点,但我不明白为什么它不起作用我正在尝试用变量文件名替换所有出现的"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)
相关文章:
- 替换变量时,JavaScript字符串replace()不起作用
- 使用replace方法替换innerHTML以及在Javascript中不起作用的正则表达式
- string.replace(“é”, “e”) 不起作用
- .replace 在 for 循环中不起作用吗?
- JavaScript Location.replace 不起作用
- YouTube ajax, .replace() 不起作用
- window.location.replace() 在窗体中不起作用
- JavaScript .replace() 部分的 url 不起作用
- 字符串正则表达式模式.replace(/{0}/, “$0.00”) 不起作用
- 使用window.location.replace重定向不起作用
- window.location.replace不起作用
- Javascript Regex replace在IE10中不起作用
- window.location.replace在客户端不起作用
- 如果重新加载了同一页,window.location.replace将不起作用
- Javascript replace()方法不起作用
- 试图更改onchange中的所有数字-onchange.replace没有'不起作用
- replace()函数在ie浏览器中不起作用
- Javascript中的Replace All不起作用
- 当我试图通过rails插入URL时,window.replace方法在js中不起作用
- Parameters .replace()两次jQuery插件不起作用