[removed] get url path

后端 未结 4 1956
借酒劲吻你
借酒劲吻你 2020-12-30 05:44
var url = \'http://domain.com/file.php?id=1\';

or

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

or



        
相关标签:
4条回答
  • 2020-12-30 05:52

    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

    0 讨论(0)
  • 2020-12-30 06:03

    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 讨论(0)
  • 2020-12-30 06:12

    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/

    0 讨论(0)
  • 2020-12-30 06:12

    this version is with regex. Try this out:

    var splittedURL = url.split(/\/+/g);
    var path = "/"+splittedURL[splittedURL.length-1];
    
    0 讨论(0)
提交回复
热议问题