如何使用javascript提取然后更改网址路径?

时间:2015-05-09 07:02:47

标签: javascript url path

我正在尝试提取部分网址,并使用javascript将其替换为自定义文字。

例如,我想获取当前网址,例如:
mydomain.com/url_part_to_change/some-other-stuff

然后更改要插入的网址,以便新的新网址为:
mydomain.com/new_url_part/some-other-stuff

这就是我所拥有的:

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

但是,当我尝试调用函数changeURL()时,它会返回undefined而不是新的网址。

例如,如果我这样做:

alert(changeURL());

那么警告是undefined

6 个答案:

答案 0 :(得分:3)

TL; DR

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

进一步说明:

Window.location(下面的图片)为您提供了一个包含所有uri部分信息的对象。因此,您可以通过window.location获取此对象并访问属性pathname然后执行您的操作。例如:

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

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

其他示例:

或者,使用location.href设置新网址。查看MDN documentation上有关location.assign()location.replace()location.reload()的示例以及不同可用功能的说明

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

// or
window.location.assign(myNewUrl)

控制台中的window.location对象

window.location

有三个参考资料可以进一步了解URI组件

  1. URI_scheme
  2. Standards written by Tim Berners-Lee
  3. MDN Location
  4. 希望这有帮助。

答案 1 :(得分:2)

这应该对你有用:

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

答案 2 :(得分:2)

你没有返回任何功能,请使功能像

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

}

答案 3 :(得分:1)

正如其他人所说,你什么也不回。他们忘记的是String.replace()只复制theURL并且不会更改theURL

试试这个:

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

  return theURL;
}
alert(changeURL());

答案 4 :(得分:0)

您忘了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.

答案 5 :(得分:0)

   function changeURL() {
      //set new path
      window.location.pathname = "/new_url_part/";

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