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

5 javascript url path

我正在尝试提取部分 url 并使用 javascript 将其替换为自定义文本。

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

然后将该 url 更改为插入,以便新的新 url 为:
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
}
Run Code Online (Sandbox Code Playgroud)

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


例如,如果我这样做:

alert(changeURL());
Run Code Online (Sandbox Code Playgroud)

那么什么是警报 undefined

小智 7

长话短说

// update the pathname that will reload the page
window.location.pathname = myNewPathname;
Run Code Online (Sandbox Code Playgroud)

进一步说明:

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 );
Run Code Online (Sandbox Code Playgroud)

其他示例:

或者,使用 设置新的 url location.href。查看MDN 文档以获取有关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)
Run Code Online (Sandbox Code Playgroud)

控制台中的 window.location 对象

窗口位置

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

  1. URI_方案
  2. Tim Berners-Lee 编写的标准
  3. MDN 位置

希望这可以帮助。


abh*_*bhi 1

您不会在函数中返回任何内容,请使函数类似于

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

}
Run Code Online (Sandbox Code Playgroud)