You need to write a function in JavaScript to return the corresponding object in the following URL string. I went to a company for an interview (the company name is not mentioned, and I may need to use this set of questions). I made a set of questions 30 minutes ago, one of which was like this:
You need to write a function in JavaScript to return the corresponding object in the following URL string.
For example:
If the input string a = '? Name = zhiyelee & blog = www.tsnrose.com ';
B = {'name': 'zhiyelee ', 'blog': 'www .tsnrose.com '} is returned '}
At that time, due to the short time, there were some problems with implementation. After coming back, I thought about it and summarized it as follows:
I have come up with two ideas: using regular expressions and using string split functions.
1. Use Regular Expressions for processing
The first thing I think of is to use regular expressions for processing. It may be that this method is more challenging and concise, but it was suspected that the efficiency of this method would be lower than the efficiency of directly using string functions for processing. This efficiency will be verified later ~
The idea of this method is very simple, that is, the regular expression is used to match a '*** = ###' string each time, and then the loop finally Retrieves all.
The Code is as follows:
The Code is as follows:
Var getNRReg = function (str ){
Var res = {};
Var reg =/(\ w +) = (\ w +)/g;
While (a = reg.exe c (str ))){
Res [a [1] = a [2];
}
Return res;
};
2. Use string functions for processing
This idea is also more common, but it must be more difficult to write than to use regular expressions.
First, use '&' to split the original string into multiple strings. The style of each string is like '*** = ###', then apply the split ('=') to the string '). (This method does not use regular expressions. Of course, we can use regular splits (/& | = /)
The Code is as follows:
The Code is as follows:
Var getNRSplit = function (str ){
Var temp, res = {},
I, ret;
Str = str. slice (1 );
Temp = str. split ('&');
For (I = 0; I <temp. length; I ++ ){
Ret = temp [I]. split ('= ');
Res [ret [0] = ret [1];
}
Return res;
}
Efficiency of the two methods
As we all know, regular expressions are a little inefficient. Therefore, we initially thought that the efficiency of the first scheme must be lower than that of the second scheme. Therefore, after the actual test, the result is not:
Execution time of 1000000 times:
The execution time of getNRReg is 4399 ms.
GetNRSplit execution time: 6116 ms
View the complete source code: jsfiddle, which can be tested by yourself ~
Ps:
The following is a written question for the front-end position of Sina Weibo at the beiyou lecture Board:
Use a regular expression to delete adjacent and identical characters. For example, after processing the "fdaffdaaklfjk" string, it becomes "fdafdakljk ".
For my answers, see jsfiddle.