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开发者_JS百科'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".
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 :)
You're specifying a string as a regex. Try specifying a substring as the 1st param to replace(), like so:
var url = "http://localhost/xxx/index.html";
url.replace('index.html','changed.html'); // add 'gi' as 3rd param for all occurrences
See docs for String.replace
From http://www.devguru.com/technologies/ecmascript/quickref/regexp_special_characters.html:
The decimal point matches any single character except the new line character. So, for instance, with the string "The cat eats moths" the regular expression /.t/gi would match the letters 'at' in 'cat', 'at' in 'eats' and 'ot' in 'moths', but not the initial 'T' of 'The'.
So you have to escape the period:
url.replace(/index\.html/gi,filenames)
精彩评论