The following two examples do the same thing.
I was wondering why Option 1 is given in a code example I found and not Option 2?
What is the significance of the forward/backward slashes in '/\&/'
Option 1.
var pairs = qString.split(/\&/);
Option 2.
var pairs = qString.split('&');
The following two examples do the same thing.
I was wondering why Option 1 is given in a code example I found and not Option 2?
What is the significance of the forward/backward slashes in '/\&/'
Option 1.
var pairs = qString.split(/\&/);
Option 2.
var pairs = qString.split('&');
Share
asked Mar 14, 2011 at 5:05
js_newbjs_newb
131 silver badge3 bronze badges
3 Answers
Reset to default 3split()
is a function that can take a regex as well as a string parameter, the forward slash usage is something called a regex literal and it is not really passing a string but a regex object.
The following statements in javascript are the same.
var regex = /\&/; // Literal
var regex = new RegExp("\\&"); // Explicit
Option 1 uses a RegEx constant which is declared with surrounding forward slashed (/
).
Option 2 uses a string.
See https://developer.mozilla/en/Core_JavaScript_1.5_Guide/Regular_Expressions
The first example splits on a regular expression (constructed using the leaning-toothpick (/.../
) syntax), while the second splits on a plain string.
Regular expressions are a powerful sub-language that allow plex string matching; in this case, the overhead of using one to split on a literal character (while probably negligible) is a little silly. It's like hiring a top-notch architect to build a wooden cube.
In the first example, the &
character is mistakenly escaped (with the \
), since it is not special in regular expressions. The regular expression engine gracefully handles that, however, and still treats it as a literal &
.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745067933a4609367.html
评论列表(0条)