Getting parts of a URL (Regex)

后端 未结 26 2221
说谎
说谎 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:47

    I realize I'm late to the party, but there is a simple way to let the browser parse a url for you without a regex:

    var a = document.createElement('a');
    a.href = 'http://www.example.com:123/foo/bar.html?fox=trot#foo';
    
    ['href','protocol','host','hostname','port','pathname','search','hash'].forEach(function(k) {
        console.log(k+':', a[k]);
    });
    
    /*//Output:
    href: http://www.example.com:123/foo/bar.html?fox=trot#foo
    protocol: http:
    host: www.example.com:123
    hostname: www.example.com
    port: 123
    pathname: /foo/bar.html
    search: ?fox=trot
    hash: #foo
    */
    

提交回复
热议问题