最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I extract and then change the url path using javascript? - Stack Overflow

programmeradmin3浏览0评论

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/url_part_to_change/some-other-stuff

and then change that url to insert so that new new url is:
mydomain/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

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

Share Improve this question edited Oct 14, 2015 at 12:17 deceze 522k88 gold badges797 silver badges938 bronze badges asked May 9, 2015 at 7:02 anonanon 9
  • 1 How and where are you calling changeURL()? You are not returning anything. – Zee 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 – Criss Lion 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. – anon Commented May 9, 2015 at 7:08
  • better to put complete code here – Ahmad Ebrahimi Commented May 9, 2015 at 7:11
  • not needed, correct answer was already given. – anon Commented May 9, 2015 at 7:21
 |  Show 4 more comments

8 Answers 8

Reset to default 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

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.

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/"); 
}

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

}

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());

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.
   function changeURL() {
      //set new path
      window.location.pathname = "/new_url_part/";

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

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)

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("/"));

发布评论

评论列表(0)

  1. 暂无评论