Getting parts of a URL (Regex)

后端 未结 26 2764
说谎
说谎 2020-11-22 02:13

Given the URL (single line):
http://test.example.com/dir/subdir/file.html

How can I extract the following parts using regular expressions:

  1. The Subd
26条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 02:50

    Here is one that is complete, and doesnt rely on any protocol.

    function getServerURL(url) {
            var m = url.match("(^(?:(?:.*?)?//)?[^/?#;]*)");
            console.log(m[1]) // Remove this
            return m[1];
        }
    
    getServerURL("http://dev.test.se")
    getServerURL("http://dev.test.se/")
    getServerURL("//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js")
    getServerURL("//")
    getServerURL("www.dev.test.se/sdas/dsads")
    getServerURL("www.dev.test.se/")
    getServerURL("www.dev.test.se?abc=32")
    getServerURL("www.dev.test.se#abc")
    getServerURL("//dev.test.se?sads")
    getServerURL("http://www.dev.test.se#321")
    getServerURL("http://localhost:8080/sads")
    getServerURL("https://localhost:8080?sdsa")
    

    Prints

    http://dev.test.se
    
    http://dev.test.se
    
    //ajax.googleapis.com
    
    //
    
    www.dev.test.se
    
    www.dev.test.se
    
    www.dev.test.se
    
    www.dev.test.se
    
    //dev.test.se
    
    http://www.dev.test.se
    
    http://localhost:8080
    
    https://localhost:8080
    

提交回复
热议问题