1

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".

3
  • Why not simply url.replace("/index.html", filenames)? Commented May 15, 2011 at 12:25
  • 2
    That code does in fact work just fine. Commented May 15, 2011 at 12:26
  • If I were you, I'd throw in an alert(filenames) to be sure you know everything that's going on. Commented May 15, 2011 at 13:11

3 Answers 3

1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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)

3 Comments

But the "." will in fact match the "." in "index.html" just fine.
@Pointy, yes... if you escape it.
It will also match a "." if you don't escape it, because "." matches any character - including ".".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.