use*_*757 24 javascript regex url
我想使用regex和replace方法从JavaScript中的绝对URL获取相对URL.
我尝试了以下但它不起作用:
var str="http://localhost/mypage.jsp";
document.write(str.replace("^[\w]*\/\/[\w]*$",""));
Run Code Online (Sandbox Code Playgroud)
lon*_*day 55
一个很好的方法是使用浏览器的本机链接解析功能,使用一个a元素:
function getUrlParts(url) {
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
hostname: a.hostname,
port: a.port,
pathname: a.pathname,
protocol: a.protocol,
hash: a.hash,
search: a.search
};
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用访问路径名getUrlParts(yourUrl).pathname.
属性与location对象的属性相同.
Tim*_*ker 25
如果"相对URL"是指第一个单词后面的字符串部分/,那么它很简单:
document.write(str.replace(/^(?:\/\/|[^\/]+)*\//, ""));
Run Code Online (Sandbox Code Playgroud)
这将匹配/字符串中第一个单词的所有字符,并用空字符串替换它们.
在:http://localhost/my/page.jsp- >出:/my/page.jsp
Sri*_*hna 25
下面的代码段返回页面的绝对URL.
var myURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
Run Code Online (Sandbox Code Playgroud)
如果您只需要相对网址,请使用以下代码段
var myURL=window.location.pathname;
Run Code Online (Sandbox Code Playgroud)
Checkout 使用Javascript获取相对URL以获取更多详细信息以及实现相同功能的多种方法.
nul*_*ble 10
const url = new URL('https://www.example.com/path/#anchor?query=value');
const rel = url.toString().substring(url.origin.length)
console.log(rel)
// Output: /path/#anchor?query=value
Run Code Online (Sandbox Code Playgroud)
不要使用像regexp等低级别的东西.这些东西已经被很多其他人解决了.特别是边缘情况.
看看URI.js,它应该做的工作:http://medialize.github.io/URI.js/docs.html#relativeto
var uri = new URI("/relative/path");
// make path relative
var relUri = uri.relativeTo("/relative/sub/foo/sub/file"); // returns a new URI instance
// relUri == "../../../path"
Run Code Online (Sandbox Code Playgroud)