开发者

javascript: get url path

开发者 https://www.devze.com 2023-02-01 02:07 出处:网络
var url = \'http://domain.com/file.php?id=1\'; or var url = \'htt开发者_StackOverflowps://domain.us/file.php?id=1\'
var url = 'http://domain.com/file.php?id=1';

or

var url = 'htt开发者_StackOverflowps://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


In Douglas Crockford's book "JavaScript: The Good Parts", there's a regex for retreiving all url parts. It's on page 66 and you can see it here: http://books.google.ch/books?id=PXa2bby0oQ0C&pg=PA66

You can copy and paste from here: 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. Then check if the index is within bounds and get substring from last slash to end of the string.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号