一些常用JS 函数总结

搜索url参数

 1 /**
 2      * 搜索url参数 
 3      * @param  {String} name 参数键名
 4      * @return {String}      对应值
 5      */
 6     function getQueryVariable(name) {
 7         var result = location.search.match(new RegExp("[?&]" + name + "=([^&]+)", "i"));
 8         if (result == null || result.length < 1) {
 9             return "";
10         }
11         return result[1];
12     };
View Code

删除字符串空格

 1     /**
 2      * 删除字符串空格
 3      * @param  {String} text 输入字符串
 4      * @return {String}      
 5      */
 6     function trim(text) {
 7 
 8         var rtrim = /^[suFEFFxA0]+|[suFEFFxA0]+$/g;
 9 
10         return text == null ?
11             "" :
12             (text + "").replace(rtrim, "");
13     };
View Code

字符串转JSON

 1     function parseJSON(data) {
 2 
 3         // Attempt to parse using the native JSON parser first
 4         if (window.JSON && window.JSON.parse) {
 5             return window.JSON.parse(data);
 6         }
 7 
 8         if (data === null) {
 9             return data;
10         }
11 
12         if (typeof data === "string") {
13 
14             var rvalidchars = /^[],:{}s]*$/,
15                 rvalidbraces = /(?:^|:|,)(?:s*[)+/g,
16                 rvalidescape = /\(?:["\/bfnrt]|u[da-fA-F]{4})/g,
17                 rvalidtokens = /"[^"\
]*"|true|false|null|-?(?:d+.|)d+(?:[eE][+-]?d+|)/g,
18                 // Make sure leading/trailing whitespace is removed (IE can't handle it)
19                 data = trim(data);
20 
21             if (data) {
22 
23                 // Make sure the incoming data is actual JSON
24                 // Logic borrowed from http://json.org/json2.js
25                 if (rvalidchars.test(data.replace(rvalidescape, "@")
26                         .replace(rvalidtokens, "]")
27                         .replace(rvalidbraces, ""))) {
28 
29                     return (new Function("return " + data))();
30                 }
31             }
32         }
33 
34         console.error("Invalid JSON: " + data);
35     };
View Code
原文地址:https://www.cnblogs.com/lonny/p/5219228.html