Home >Web Front-end >JS Tutorial >Implement code through regular formatted url query string_javascript skills

Implement code through regular formatted url query string_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:44:561058browse

I saw that the query string was formatted through the js array split method in the project, and I suddenly wondered why I couldn't use regular expressions. How is the performance? So we have the following code:

Copy code The code is as follows:

var url='www .baidu.com?a=123&b=456&c=789&e=dfsdfsdfsdfsdfsdfsdf&f=46545454545454785&g=e23232dsfvdfvdf';
/**
* Formatted query string (regular implementation)
* @param url url address
* @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;
}
/**
* Formatted query string (array implementation)
* @param url url address
* @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;iitem= 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 implemented function is actually better than the array The implemented function should be slower (tears...). But fortunately, it is only 0.4 seconds slower when repeated a million times.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn