Could you please help me understand this javascript RegExp :
cbreg = new RegExp('((^|\\?|&)' + cbkey + ')=([^&]+)')
// where cbkey is a string
I am confused by the (^|\\?|&)
portion. What could that mean?
Thanks !
Could you please help me understand this javascript RegExp :
cbreg = new RegExp('((^|\\?|&)' + cbkey + ')=([^&]+)')
// where cbkey is a string
I am confused by the (^|\\?|&)
portion. What could that mean?
Thanks !
Share Improve this question asked Jun 4, 2012 at 20:45 cedricbelletcedricbellet 1482 silver badges12 bronze badges 3- developer.mozilla/en/JavaScript/Reference/Global_Objects/… – hugomg Commented Jun 4, 2012 at 20:52
- In case anyone's interested, the code is from here github./ded/reqwest/blob/master/src/reqwest.js#L76 and means callback regex, and parses the JSONP callback function name from a query string – Esailija Commented Jun 4, 2012 at 20:55
- Thank you for the reference I think I read the article about Regular expressions on MDN instead of the one on RegExp. And also @Esailija you're right, the code sample es from ded/reqwest. Thanks for mentioning it. – cedricbellet Commented Jun 4, 2012 at 20:58
4 Answers
Reset to default 7Well first of all given that the regex is created from a string literal the double backslashes bee only a single backslash in the resulting regex (because that's how escaping works in a string literal):
(^|\?|&)
The |
means OR, so then you have:
^ - start of line, or
\? - a question mark, or
& - an ampersand
A question mark on its own has special meaning within a regex, but an escaped question mark matches an actual question mark.
The parentheses means it matches one of those choices before matching the next part of the regex. Without parens the third choice would include the next part of the expression (whatever is in cbkey
).
It means either (|
) the start of the string (^
), a literal question (\?
because the question mark needs to be escaped in regexes and \\?
because the backslash needs to be escaped in strings) mark or an ampersand (&
).
|
means "OR". So that means: ^
(start of line) OR ?
OR &
.
It searches for the block (the parentheses mean a block) which must start (^ = must start with) with character '?' or (| = or) character '&'.