7

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

deceze
  • 491,798
  • 79
  • 706
  • 853

7 Answers7

5

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.

Community
  • 1
  • 1
daxeh
  • 1,055
  • 8
  • 11
  • hmm, seems a bit much, others address the issue directly when you are just posting a bunch of stuff that it too confusing. – john smith May 09 '15 at 09:02
  • 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. – daxeh May 09 '15 at 23:16
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/"); 
}
Criss Lion
  • 209
  • 1
  • 7
  • 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) and [playground](http://www.regexr.com/) It allows you to match strings that would be a complete pain matching with basic string functions. – Criss Lion May 09 '15 at 07:15
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

}
abhi
  • 1,027
  • 9
  • 19
  • 1
    this answer is wrong as it just returns the original url not the new one. – john smith May 09 '15 at 09:01
  • 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 – abhi May 09 '15 at 10:15
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());
JanS
  • 2,025
  • 3
  • 24
  • 27
  • 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/" – JanS May 09 '15 at 07:57
  • 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. – john smith May 09 '15 at 09:03
1
   function changeURL() {
      //set new path
      window.location.pathname = "/new_url_part/";

      //get new url
      const newURL = window.location.href;
      return newURL;
    }
  • 1
    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. – Alexander Feb 19 '19 at 17:18
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.
Zee
  • 8,300
  • 5
  • 34
  • 58
  • This returns original URL not the changed one. – john smith May 09 '15 at 07:11
  • 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?! :) – john smith May 09 '15 at 07:19
  • 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 :'( – john smith May 09 '15 at 07:22
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)
mike
  • 381
  • 3
  • 5