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