我正在尝试提取部分 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
}
但是,当我尝试调用该函数时changeURL()
,它返回undefined
而不是新的网址。
例如,如果我这样做:
alert(changeURL());
那么警报是什么undefined
TL;DR
// update the pathname that will reload the page
window.location.pathname = myNewPathname;
进一步说明:
窗口位置 https://developer.mozilla.org/en-US/docs/Web/API/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 文档 https://developer.mozilla.org/en-US/docs/Web/API/Window/location例如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 对象
进一步了解 URI 组件有三个参考资料
- URI_方案 http://en.wikipedia.org/wiki/URI_scheme
- Tim Berners-Lee 编写的标准 https://www.rfc-editor.org/rfc/rfc3986#section-3.5
- MDN 位置 https://developer.mozilla.org/en-US/docs/Web/API/Location
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)