从绝对URL获取相对URL [英] Get relative URL from absolute URL
本文介绍了从绝对URL获取相对URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用正则表达式和替换方法从JavaScript中的绝对URL获取相对URL。
I want to get the relative URL from an absolute URL in JavaScript using regex and the replace method.
我尝试了以下但是它无效:
I tried the following but it is not working:
var str="http://localhost/mypage.jsp";
document.write(str.replace("^[\w]*\/\/[\w]*$",""));
推荐答案
如果通过相对网址,则指的是第一个单词 /
之后的字符串,那很简单:
If by "relative URL" you mean the part of the string after the first single /
, then it's simple:
document.write(str.replace(/^(?:\/\/|[^\/]+)*\//, ""));
这匹配所有字符直到第一个 / $ c字符串中的$ c>并用空字符串替换它们。
This matches all the characters up to the first single /
in the string and replaces them with the empty string.
输入: http://localhost/my/page.jsp
- > Out: /my/page.jsp
In: http://localhost/my/page.jsp
--> Out: /my/page.jsp
这篇关于从绝对URL获取相对URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文