AutoHotkey 参考 JavaScript 的 window.location 对网址进行分解

在JavaScript里,window.location有各种参数,对于分析网址很方便,于是AutoHotkey也写了个

假如有如下网址

http://www.a.com.cn:80/dir/aa.html?ver=1#h

则分解后内容如下所示

href     http://www.a.com.cn:80/dir/aa.html?ver=1#h
protocol http:
origin   http://www.a.com.cn:80
host     www.a.com.cn:80
hostname www.a.com.cn
domain   a.com.cn
main     a
port     80
pathname /dir/aa.html
search   ?ver=1
hash     #h

附上AutoHotkey代码,其中 domain和main 的获取需要改进。

如果指定了key,则返回字符串,否则返回格式是对象

/*
http://www.a.com.cn:80/dir/aa.html?ver=1#h
href    http://www.a.com.cn:80/dir/aa.html?ver=1#h
protocol    http:
origin    http://www.a.com.cn:80
host    www.a.com.cn:80
hostname    www.a.com.cn
domain    a.com.cn
main    a
port    80
pathname    /dir/aa.html
search    ?ver=1
hash    #h
*/
location(url, key:="") {
    obj := {}
    ;href (前面添加 http://,后面删除/)
    obj.href := rtrim(url, "/")
    if (!instr(obj.href,"//"))
        obj.href := "http://" . obj.href
    arr := StrSplit(obj.href, "/")
    obj.protocol := arr[1]
    obj.origin := StrLower(format("{1}//{2}",arr[1],arr[3]))
    obj.host := StrLower(arr[3])
    ; hostname 和 port
    if instr(obj.host, ":") {
        arr := StrSplit(obj.host, ":")
        obj.hostname := arr[1]
        obj.port := arr[2]
    } else {
        obj.hostname := obj.host
        obj.port := ""
    }
    ;获取 domain
    if (obj.hostname ~= "^d+(.d+){3}$") {
        obj.main := ""
        obj.domain := obj.hostname
    } else {
        arr := StrSplit(obj.hostname, ".")
        l := arr.length()
        if (arr[l] == "cn" && arr[l-1] == "com") { ;TODO 需完善
            obj.main := arr[l-2]
            obj.domain := format("{1}.{2}.{3}", obj.main,arr[l-1],arr[l])
        } else {
            obj.main := arr[l-1]
            obj.domain := format("{1}.{2}", obj.main,arr[l])
        }
    }
    ;处理 origin 后面的内容
    sNow := substr(obj.href, strlen(obj.origin)+1)
    ;先获取末尾的 hash
    if instr(sNow,"#") {
        obj.hash :=  "#" . RegExReplace(sNow, ".*#")
        sNow := substr(sNow, 1, strlen(sNow)-strlen(obj.hash))
    } else
        obj.hash := ""
    ;再获取 search
    if instr(sNow,"?") {
        obj.search :=  "?" . RegExReplace(sNow, ".*?")
        sNow := substr(sNow, 1, strlen(sNow)-strlen(obj.search))
    } else
        obj.search := ""
    ;剩余即是 pathname
    obj.pathname := sNow
    return (strlen(key) && obj.haskey(key)) ? obj[key] : obj
}