[英]javascript: get url path
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';
你可以用正则表达式来做,但使用这些原生属性可以说是最好的方法。
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:The Good Parts”中,有一个用于检索所有url部分的正则表达式。 它位于第66页,您可以在此处看到它: http : //books.google.ch/books?id = PXa2bby0oQ0C&g = PA66
你可以从这里复制和粘贴: http : //www.coderholic.com/javascript-the-good-parts/
这个版本是正则表达式。 试试这个:
var splittedURL = url.split(/\/+/g);
var path = "/"+splittedURL[splittedURL.length-1];
使用string.lastIndexOf(searchstring,start)而不是正则表达式。 然后检查索引是否在边界内并从最后一个斜杠到字符串结尾获取子字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.