How to parse a URL?

前端 未结 6 615

If there is one thing I just cant get my head around, it\'s regex.

So after a lot of searching I finally found this one that suits my needs:

function         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 03:40

    The RFC (see appendix B) provides a regular expression to parse the URI parts:

    ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
     12            3  4          5       6  7        8 9
    

    where

    scheme    = $2
    authority = $4
    path      = $5
    query     = $7
    fragment  = $9
    

    Example:

    function parse_url(url) {
        var pattern = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
        var matches =  url.match(pattern);
        return {
            scheme: matches[2],
            authority: matches[4],
            path: matches[5],
            query: matches[7],
            fragment: matches[9]
        };
    }
    console.log(parse_url("http://www.somesite.se/blah/sdgsdgsdgs"));
    

    gives

    Object
        authority: "www.somesite.se"
        fragment: undefined
        path: "/blah/sdgsdgsdgs"
        query: undefined
        scheme: "http"
    

    DEMO

提交回复
热议问题