javascript: 获取 url 路径

标签 javascript regex url

var url = 'http://domain.com/file.php?id=1';

var url = 'https://domain.us/file.php?id=1'

var url = 'domain.de/file.php?id=1';

var url = 'subdomain.domain.com/file.php?id=1'

在上述情况下,我想从这些网址中的任何一个获取仅路径:

var path = '/file.php?id=1';

最佳答案

可以使用正则表达式来做到这一点,但使用这些 native 属性可以说是最好的方法。

var url = 'subdomain.domain.com/file.php?id=1',
    a = document.createElement('a');

a.href = 'http://' + url;
var path = a.pathname + a.search; // /file.php?id=1

See it on jsFiddle.net

关于javascript: 获取 url 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4497531/

相关文章:

javascript - 检查模式是否不匹配

javascript - 刷新时重定向到不同的 URL

javascript - 自调用函数javascript

javascript - 在 beforeprint 事件上使用 JQuery

Python搜索字符串包含字符

javascript - 用于获取 URL 中特定查询字符串变量的正则表达式

php - file_get_contents 从谷歌获取的文件与浏览器中显示的不同

java - 通过服务器调用 Web 服务会导致 java.net.MalformedURLException : no protocol

javascript - 当链接仅为 "#"时,防止路由参数更改 View

java - 多个拖放文件输入 - 添加下一个文件和最大文件限制