代码改变世界

Javasript获取和设置url中参数的值

2010-01-07 14:26  xiaosuo  阅读(493)  评论(0编辑  收藏  举报
url = window.location.href;
function getQueryString(key){
    var result = url.match(new RegExp("[\?\&]"+key+"=([^\&]*)(\&?)","i"));
    return result ? result [1]:result;
}

function setKeyValue(key,value){
    if(getQueryString(key) != null){
        var reg = new RegExp("([\?\&])(" + key + "=)([^\&]*)(\&?)","i");
        return url.replace(reg,"$1$2" + value + "$4");
    }else{
        var add = arguments[2];
        if(add === true)
            return url+ (url.indexOf("?") > -1 ? "&" : "?") + key + "=" + value;
        else
     return this;
    }
}