JS实用代码收集

1.JSON对象转换为字符串

//JSON对象转字符串

function jsonParseString(o) {

    try {

        if (o == undefined) { return ""; }

        var r = [];

        if (typeof o == "string") return "\"" + o.replace(/([\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";

        if (typeof o == "object") {

            if (!o.sort) {

                for (var i in o)

                    r.push("\"" + i + "\":" + jsonParseString(o[i]));

                if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {

                    r.push("toString:" + o.toString.toString());

                }

                r = "{" + r.join() + "}"

            } else {

                for (var l = 0; l < o.length; l++)

                    r.push(jsonParseString(o[l]))

                r = "[" + r.join() + "]";

            }

            return r;

        }

        return o.toString().replace(/\"\:/g, '":""');

    } catch (e) { return e.Message; }

}

 2.将指定的Javascript对象和方法编译为脚本字符串

function functionParseString(object) {

    /// <summary>将指定的Javascript对象编译为脚本</summary>

    if (!object) return null;



    var t = typeof (object);

    if (t == "string") {

        return "\"" + object.replace(/(\r|\n|\\)/gi, function (a, b) {

            switch (b) {

                case "\r":

                    return "\\r";

                case "\n":

                    return "\\n";

                case "\\":

                    return "\\\\";

            }

        }) + "\"";

    }

    if (t != "object") return object + "";



    var code = [];

    for (var i in object) {

        var obj = object[i];

        var objType = typeof (obj);



        if ((objType == "object" || objType == "string") && obj) {

            code.push(i + ":" + buildObjectJavascriptCode(obj));

        } else {

            code.push(i + ":" + obj);

        }

    }



    return "{" + code.join(",") + "}";

}

 调用方式为: eval("(" + buildObjectJavascriptCode(Test)+")()");

 3.取URL参数

//取URL参数

function Request(name) {

    try {

        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");

        var r = window.location.search.substr(1).match(reg);

        if (r != null) return unescape(r[2]); return "";

    } catch (e) {

        return e.Message;

    }

}

 

你可能感兴趣的:(js)