Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript:获取url路径_Javascript_Regex_Url - Fatal编程技术网

javascript:获取url路径

javascript:获取url路径,javascript,regex,url,Javascript,Regex,Url,或 或 或 从这些URL中的任何一个,我只想获得路径,在上述情况下: var url = 'subdomain.domain.com/file.php?id=1' 您可以使用正则表达式来实现这一点,但使用这些本机属性可以说是实现这一点的最佳方法 var path = '/file.php?id=1'; 使用string.lastIndexOf(searchstring,start)代替正则表达式。然后检查索引是否在范围内,并获取从最后一个斜杠到字符串末尾的子字符串。此版本使用正则表达式。试试

从这些URL中的任何一个,我只想获得路径,在上述情况下:

var url = 'subdomain.domain.com/file.php?id=1'
您可以使用正则表达式来实现这一点,但使用这些本机属性可以说是实现这一点的最佳方法

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

使用string.lastIndexOf(searchstring,start)代替正则表达式。然后检查索引是否在范围内,并获取从最后一个斜杠到字符串末尾的子字符串。

此版本使用正则表达式。试试这个:

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

在Douglas Crockford的书“JavaScript:好的部分”中,有一个用于检索所有url部分的正则表达式。在第66页,你可以在这里看到:


您可以从这里复制和粘贴:

Great Response alex,但是如果url类似于'subdomain.domain.com/myfiles/file.php?id=1',我只想得到'/file.php?id=1',我应该使用regex,no?@steweb在这种情况下,使用上面的代码获得路径,然后
path.replace(/^\/[^\/]+/,'')完全低估了答案。很聪明,但只适用于浏览器环境。例如,您无法在Node.js中运行它。此外,这一切都归结为字符串操作,因此使用DOM元素来进行操作有点尴尬。我不是投反对票,只是说;)@我当然同意你的看法。让浏览器为您执行字符串操作很方便,但幸运的是,在Node中,我敢打赌已经有一堆模块支持此操作。只是一个建议,您可以使用
splittedURL.pop()
获取最后一个成员:)非常感谢alex,我不知道pop()-wtf:)另请参见
var url = 'subdomain.domain.com/file.php?id=1'
var path = '/file.php?id=1';
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
var splittedURL = url.split(/\/+/g);
var path = "/"+splittedURL[splittedURL.length-1];