Javascript 从绝对 URL 获取相对 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6263454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get relative URL from absolute URL
提问by user549757
I want to get the relative URL from an absolute URL in JavaScript using regex and the replace method.
我想使用正则表达式和替换方法从 JavaScript 中的绝对 URL 获取相对 URL。
I tried the following but it is not working:
我尝试了以下但它不起作用:
var str="http://localhost/mypage.jsp";
document.write(str.replace("^[\w]*\/\/[\w]*$",""));
回答by lonesomeday
A nice way to do this is to use the browser's native link-parsing capabilities, using an a
element:
一个很好的方法是使用浏览器的原生链接解析功能,使用一个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
};
}
You can then access the pathname with getUrlParts(yourUrl).pathname
.
然后,您可以使用getUrlParts(yourUrl).pathname
.
The properties are the same as for the location
object.
属性与location
对象相同。
回答by Srinivas Ramakrishna
Below snippet returns the absolute URL of the page.
下面的代码段返回页面的绝对 URL。
var myURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
If you need only the relative url just use below snippet
如果您只需要相对网址,请使用以下代码段
var myURL=window.location.pathname;
Checkout get relative URL using Javascriptfor more details and multiple ways to achieve the same functionality.
Checkout使用 Javascript 获取相对 URL 以获取更多详细信息以及实现相同功能的多种方法。
回答by Tim Pietzcker
If by "relative URL" you mean the part of the string after the first single /
, then it's simple:
如果“相对 URL”是指第一个 single 之后的字符串部分/
,那么它很简单:
document.write(str.replace(/^(?:\/\/|[^/]+)*\//, ''));
This matches all the characters up to the first single /
in the string and replaces them with the empty string.
这将匹配/
字符串中第一个字符之前的所有字符,并将它们替换为空字符串。
In: http://localhost/my/page.jsp
--> Out: /my/page.jsp
输入:http://localhost/my/page.jsp
--> 输出:/my/page.jsp
回答by koppor
Don't use low-level stuff like regexp etc. These things have been solved by so many other people. Especially the edge cases.
不要使用像regexp等低级的东西。这些东西已经被很多其他人解决了。尤其是边缘情况。
Have a look at URI.js, it should do the job: http://medialize.github.io/URI.js/docs.html#relativeto
看看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"
回答by LeleDumbo
don't forget that \
is an escape character in strings, so if you would like to write regex in strings, ensure you type \
twice for every \
you need. Example: /\w/
→ "\\w"
不要忘记这\
是字符串中的转义字符,因此如果您想在字符串中编写正则表达式,请确保\
为每个\
需要键入两次。示例:/\w/
→"\\w"
回答by m93a
URL.getRelativeURL
URL.getRelativeURL
There's an public-domain extension for the standard URL
object called getRelativeURL
.
It's got a few cool tweaks like force reload, you should check it out!
标准URL
对象有一个公共域扩展名为getRelativeURL
.
它有一些很酷的调整,比如强制重新加载,你应该检查一下!
Try it live.? ? ? View on Gist.
现场试一下。? ? ? 查看要点。
Example usage
示例用法
//syntax: <URL to convert>.getRelativeURL(<relative to this URL>)
//link from Mypage to Google
a = new URL("https://google.com/search");
a.getRelativeURL("https://mypage.com")
== "//google.com/search";
//link from the current location.href
a.getRelativeURL();
//link from Olutsee to Polk
var from = new URL("http://usa.com/florida/baker/olutsee");
var to = new URL("http://usa.com/florida/polk");
to.getRelativeURL(from) == "../../polk";
回答by Shivasagar
Below you can find script on that here we have only one problem which is one manual work, we want to add split attribute ie, if your site link is: Get relative URL from absolute URL
您可以在下面找到脚本,这里我们只有一个问题,这是一项手动工作,我们想添加拆分属性,即,如果您的站点链接是:从绝对 URL 获取相对 URL
we want to url as below: /questions/6263454/get-relative-url-from-absolute-url
我们想网址如下:/questions/6263454/get-relative-url-from-absolute-url
so in below code we have to add .com instead of .net ie, var res = at.split(".net"); here we want to add as per our requirement now i need to seperate after .com so code will be "var res = at.split(".com");".
所以在下面的代码中,我们必须添加 .com 而不是 .net,即 var res = at.split(".net"); 这里我们想根据我们的要求添加,现在我需要在 .com 之后分开,所以代码将是“var res = at.split(".com");”。
i think you guys got that point if you have still doubt let me know please and to see changes in code by inspecting:
我想你们明白了这一点,如果你仍然有疑问,请告诉我,并通过检查来查看代码的变化:
$(document).ready(function(){
$("a").each(function(){
var at= $(this).attr("href");
var res = at.split(".net");
var res1 = res[0];
var res2 = res[1];
alert(res2);
$(this).attr("href",res2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
<a href="https://jsfiddle.net/boilerplate/jquery2">Change color</a>
</div>
<div id="banner-message">
<p>Hello World</p>
<a href="https://jsfiddle.net/boilerplate/jquery3">Change color</a>
</div>
回答by nullable
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