从绝对 URL 获取相对 URL [英] Get relative URL from absolute URL

查看:34
本文介绍了从绝对 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]*$",""));

推荐答案

如果相对 URL"是指第一个 / 之后的字符串部分,那么很简单:

If by "relative URL" you mean the part of the string after the first single /, then it's simple:

document.write(str.replace(/^(?://|[^/]+)*//, ''));

这会匹配字符串中直到第一个 / 的所有字符,并将它们替换为空字符串.

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 --> 输出:/my/page.jsp

In: http://localhost/my/page.jsp --> Out: /my/page.jsp

这篇关于从绝对 URL 获取相对 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆