在js中获取query string 以及重写URL的函数

页面导航:首页 > 网络编程 > JavaScript > 在js中获取query string 以及重写URL的函数

在js中获取query string 以及重写URL的函数

来源: 作者: 时间:2016-01-23 10:23 【

函数用途:如标题,1 从URL中解析出参数,2 重写URL中的参数值如下代码所示,包含了测试。可以直接copy到浏览器中,输入测试地址:localhost:xxx?a=1c=3 ,在console中运行查看结果: - test

函数用途:如标题,1. 从URL中解析出参数,2.重写URL中的参数值

 

如下代码所示,包含了测试。可以直接copy到中,输入测试地址:localhost:xxx?a=1&b=2&c=3 ,在console中运行查看结果:

 

// - test

// - get from current location
var url = document.location.href;

// - extract param from url
console.log(getUrlParam(url,"a") == "1");
console.log(getUrlParam(url,"b") == "2");
console.log(getUrlParam(url,"c") == "3");

// - rewrite url
url = setUrlParam(url,"a",3);
url = setUrlParam(url,"b",1);
url = setUrlParam(url,"c",2);

console.log(getUrlParam(url,"a") == "3");
console.log(getUrlParam(url,"b") == "1");
console.log(getUrlParam(url,"c") == "2");


// - helper functions

 function getUrlParam(location,name) {
        var url = location;
        var splitIndex = url.indexOf("?") + 1;
        var paramStr = url.substr(splitIndex, url.length);

        var arr = paramStr.split('&');
        for (var i = 0; i < arr.length; i++) {
            var kv = arr[i].split('=');
            if (kv[0] == name) {
                return kv[1];
            }
        }
        return "";
    }

    function setUrlParam(location,name, value) {
        var url = location;
        var splitIndex = url.indexOf("?") + 1;
        var paramStr = url.substr(splitIndex, url.length);

        var newUrl = url.substr(0, splitIndex);

        // - if exist , replace 
        var arr = paramStr.split('&');
        for (var i = 0; i < arr.length; i++) {
            var kv = arr[i].split('=');
            if (kv[0] == name) {
                newUrl += kv[0] + "=" + value;
            } else {
                if (kv[1] != undefined) {
                    newUrl += kv[0] + "=" + kv[1];
                }
            }
            if (i != arr.length - 1) {
                newUrl += "&";
            }
        }

        // - if new, add
        if (newUrl.indexOf(name) < 0) {
            newUrl += splitIndex == 0 ? "?" + name + "=" + value : "&" + name + "=" + value;
        }
        return newUrl;
    }
IE中运行结果:

 

\


 

Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<