·
Across the Great Wall, we can reach every corner in the world.

试试这个:

/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/

参考这里:用正则表达式分析 URL。(文章有详细解释)

var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var url = "https://harttle.land:80/tags.html?simple=true#HTML",
    result = parse_url.exec(url);
    blanks = '       ';
    fields = ['url', 'scheme', 'slash', 'host', 'port', 'path', 'query', 'hash'];
fields.forEach(function(field, i){
    console.log(field + ':' + blanks.substr(field.length) + result[i]);
});

可以解析出:

url:    https://harttle.land:80/tags.html?simple=true#HTML
scheme: http
slash:  //
host:   harttle.land
port:   80
path:   tags.html
query:  single=true
hash:   HTML

这个网站可以看到正则的状态机结构,方便调试:

Replies
1

状态机这个网站很 nice!收藏了 heart