简体   繁体   English

javascript:获取网址路径

[英]javascript: get url path

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

or 要么

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

or 要么

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

or 要么

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

from either one of these urls I want to get only the path , in the case above: 从上述任何一个网址中我只想获得路径 ,在上面的例子中:

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

You could do it with regex, but using these native properties are arguably the best way to do it. 可以用正则表达式来做,但使用这些原生属性可以说是最好的方法。

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 在jsFiddle.net上看到它

In Douglas Crockford's book "JavaScript: The Good Parts", there's a regex for retreiving all url parts. 在Douglas Crockford的书“JavaScript:The Good Parts”中,有一个用于检索所有url部分的正则表达式。 It's on page 66 and you can see it here: http://books.google.ch/books?id=PXa2bby0oQ0C&pg=PA66 它位于第66页,您可以在此处看到它: http//books.google.ch/books?id = PXa2bby0oQ0C&g = PA66

You can copy and paste from here: http://www.coderholic.com/javascript-the-good-parts/ 你可以从这里复制和粘贴: http//www.coderholic.com/javascript-the-good-parts/

this version is with regex. 这个版本是正则表达式。 Try this out: 试试这个:

var splittedURL = url.split(/\/+/g);
var path = "/"+splittedURL[splittedURL.length-1];

Use string.lastIndexOf(searchstring, start) instead of a regex. 使用string.lastIndexOf(searchstring,start)而不是正则表达式。 Then check if the index is within bounds and get substring from last slash to end of the string. 然后检查索引是否在边界内并从最后一个斜杠到字符串结尾获取子字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM