10

I am trying to extract part of the url and replace it with custom text using javascript.

For example, I want to fetch the current url such as:
mydomain.com/url_part_to_change/some-other-stuff

and then change that url to insert so that new new url is:
mydomain.com/new_url_part/some-other-stuff

Here is what I have:

function changeURL() {
        var theURL = window.location.pathname;
        theURL.replace("/url_part_to_change/", "/new_url_part/");
        //Set URL
}

However, when I try to call the function changeURL(), it returns undefined instead of the new url.


For example if I do this:

alert(changeURL());

then what alerts is undefined

9
  • 1
    How and where are you calling changeURL()? You are not returning anything. Commented May 9, 2015 at 7:05
  • @sdfasdf acdsgcxzg I think you missed the return statement, without that functions do not return anything, just compute Commented May 9, 2015 at 7:06
  • @CrissLion lyon: yes, thank you, please tell me how to fix. I tried adding return; after //set URL but it still returns undefined. Edit: I just saw your answer, thank you! I will try. Commented May 9, 2015 at 7:08
  • better to put complete code here Commented May 9, 2015 at 7:11
  • not needed, correct answer was already given. Commented May 9, 2015 at 7:21

8 Answers 8

7

TL;DR

// update the pathname that will reload the page
window.location.pathname = myNewPathname;

Further Explanation:

Window.location ( image attached below ) provides you an object containing all the uri parts information. So, you can get this object via window.location and access the property pathname then do your stuffs. For example:

var locationObject = window.location;
var pathnameToChange = locationObject.pathname;

// do stuffs to "copy" of pathname, this will not reload the page
var myNewPathname = doSomethingMyPathname( pathnameToChange );

Additional Examples:

Alternatively, set new url using location.href. Check the MDN documentation for examples on location.assign(), location.replace(), location.reload() and notes on the different available functions

// ie.myNewUrl is something I created -> www.blah.com/updated/path
window.location.href = myNewUrl; 

// or
window.location.assign(myNewUrl)

A window.location Object in Console

window.location

There are three references to further understand URI components

  1. URI_scheme
  2. Standards written by Tim Berners-Lee
  3. MDN Location

Hope this helps.

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

2 Comments

hmm, seems a bit much, others address the issue directly when you are just posting a bunch of stuff that it too confusing.
ah, the first part was a direct answer, next few parts are for understanding and also references. it may help you or others, perhaps i should have made it clear.. ill add that TLDR; thanks.
2

This should work for you correctly:

function changeURL() {
        // Get the url, just as you did
        var theURL = window.location.pathname;
        // Return the url
        return theURL.replace("/url_part_to_change/", "/new_url_part/"); 
}

1 Comment

Just for educational purpose - if you need to match url parts that could have variable content like user name, you could use regular expressions! RegEx is one of the topics people avoid, but is really useful reference and playground It allows you to match strings that would be a complete pain matching with basic string functions.
1

you are not returning any thing in function, Please make function like

function changeURL() {
        var theURL = window.location.pathname;
       return  theURL.replace("/url_part_to_change/", "/new_url_part/");
        //Set URL

}

2 Comments

this answer is wrong as it just returns the original url not the new one.
ok Sorry for that you need new variable to return that or simply return it, but while answering this i was more focused on undefined error, will edit it right away
1

As the others said, you don't return anything. What they are forgetting is that String.replace() just makes a copy of theURL and doesn't change theURL.

Try this:

function changeURL() {
  var theURL = window.location.pathname;
  theURL = theURL.replace("/url_part_to_change/", "new_url_part/");
  //Set URL

  return theURL;
}
alert(changeURL());

2 Comments

I forgot to change the url that I used at JsFiddle. I edited the above post to include the correct url "/url_part_to_change/"
still nope, look at Criss Lion's answer to see what you did wrong. your answer just returns the original answer instead of the new one.
0

You forgot to return

function changeURL() {
    var theURL = window.location.pathname;
    var newURL = theURL.replace("/url_part_to_change/", "/new_url_part/");
    //Set URL
    return newURL;
}

alert(changeURL())//Now you won't see undefined.

3 Comments

This returns original URL not the changed one.
yes this would work also it looks like. But Criss Lion gave a correct answer first. Thank you for your answer as this also seems correct. Too bad I can't choose two best answers?! :)
i would upvote as you requested but upvote requires 15 rep and since someone downvoted my question I am back to 0 rep :( I tried to upvote, if that is any consolance :'(
0
   function changeURL() {
      //set new path
      window.location.pathname = "/new_url_part/";

      //get new url
      const newURL = window.location.href;
      return newURL;
    }

2 Comments

While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
the assignment to pathname will change the url, making the last two lines superfluous
0

This is quite an old post but just to add:

modifying window.location causes page navigations so if thats not desired create a new URL object and then you can modify the parts as needed.

in my case i needed to change the path to a value from a value in the querystring.

eg.

/*
 * http://something.com/some/path?redirect=/some/other/path
 * ->
 * http://something.com/some/other/path
 */

let u = new URL(window.location.href)
u.pathname=u.searchParams.get("redirect")
u.searchParams.delete("redirect")
console.log(u.href)

Comments

0

The URL Constructor is probably the best tool for the job.

let urlString = "http://example.com:8080/url_part_to_change/some-other-stuff";
let url = new URL(urlString);
let path = url.pathname;
let base = url.href.replace(path,"");

let pathArray = path.split("/");
pathArray.forEach(function(p, i){
 console.log(i, p)
});
pathArray[1] = "new";

console.log(base + pathArray.join("/"));

Comments

Your Answer

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