I can see that the project uses the js array split method to format the query string. Why cannot I use regular expressions? What is the performance? The following code is available:
Copy codeThe Code is as follows: var url = 'www .baidu.com? A = 123 & B = 456 & c = 789 & e = dfsdfsdfsdfsdfsdf & f = 46545454545454785 & g = e23232dsfvdfvdf ';
/**
* Format the query string (regular expression)
* @ Param url
* @ Return {Object} formatted json Object
*/
Function formatUrl (url ){
Var reg = /(? :[? &] +) ([^ &] +) = ([^ &] +)/G;
Var data = {};
Function fn (str, pro, value ){
Data [decodeURIComponent (pro)] = decodeURIComponent (value );
}
Url. replace (reg, fn );
Return data;
}
/**
* Format the query string (Array Implementation)
* @ Param url
* @ Return {Object} formatted json Object
*/
Function formatUrl2 (url ){
Url = url. replace (/.*\? /,'');
Var args = {},
Items = url. length? Url. split ("&"): []
, Item = null
, I = 0
, Len = items. length;
For (I = 0; I <items. length; I ++ ){
Item = items [I]. split ("= ");
Args [decodeURIComponent (item [0])] = decodeURIComponent (item [1]);
}
Return args;
}
Var startTime = new Date ();
For (var I = 0; I <1000000; I ++ ){
FormatUrl2 (url );
}
Console. log ('formaturl2 ', (new Date ()-startTime); // formatUrl2 12138
StartTime = new Date ();
For (var I = 0; I <1000000; I ++ ){
FormatUrl (url );
}
Console. log ('formaturl', (new Date ()-startTime); // formatUrl 12537
The test browser is chrme 25; the regular expression function is slower than the function implemented by the array ....). But fortunately, it takes only 1 million seconds to repeat the execution for 0.4 times.