What does /;/ and /^ +/ denote?
I recently came across the statement :
var cookies = document.cookie.split(/;/);
and
var pair = allCookies[i].split("=", 2);
if (pair[0].replace(/^ +/, "") == "lastvisit")
In the first statement what does /;/
in the argument of split denote ?
In the second statement what does /^ +/
开发者_如何学编程in the argument of replace denote ?
These are Regular Expressions.
Javascript supports them natively.
In this particular example:
.split(/;/)
uses;
as the split character;.replace(/^ +/, "")
removes (""
) any (+
) leading (^
) whitespace ().
In both examples, /
surround or delimit the regular expression (or "regex"), informing Javascript that you're providing a regex.
Follow the links provided above for more information; regexes are broad in scope and worth learning.
Slashes delimit a regular expression, just like quotes delimit a string.
/;/ matches a semi-colon. Specifically:
var cookies = document.cookie.split(/;/);
Means we split the document.cookie string into an array, splitting it where there are semicolons. So it would take something like "a;b;c" and turn it into ["a", "b", "c"].
pair[0].replace(/^ +/, "")
Just strips all leading whitespace. It turns
" lastvisit"
into
"lastvisit"
The caret ^ means "beginning of line", it's followed by space, and the + means to repeat the space one or more times, as many as possible.
The //
syntax denotes a regular expression (also known as a 'regex').
Regex is a syntax for searching and replacing strings.
The first example you gave is /;/
. This is a very simply regex which just searches the string for semi-colons, and then splits it into an array based on the result. Since this is not using any special regex functionality, it could just as easily have been expressed as a simple string, ie split(";")
(as has been done with the equal sign in your other example), without making any difference to the result.
The second example is /^ +/
. This is more complex and requires a bit of knowledge of how regex works. In short, what it is doing is searching for leading spaces on a string, and removing them.
To learn more about regex, I recommend this site as a good starting point: http://www.regular-expressions.info/
Hope that helps.
I think that /^ +/ means: one or more no-" " characters
精彩评论