cedricbellet
cedricbellet

Reputation: 148

RegExp (^|\\?|&) in javascript

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 !

Upvotes: 0

Views: 4114

Answers (4)

nnnnnn
nnnnnn

Reputation: 150020

Well first of all given that the regex is created from a string literal the double backslashes become 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).

Upvotes: 7

hugomg
hugomg

Reputation: 69934

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 (&).

Upvotes: 2

jlink
jlink

Reputation: 692

It searches for the block (the parentheses mean a block) which must start (^ = must start with) with character '?' or (| = or) character '&'.

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227220

| means "OR". So that means: ^ (start of line) OR ? OR &.

Upvotes: 1

Related Questions