views:

34

answers:

1

Hello, how do I match this phone number in Javascript?

> str
"(555) 555-3300"
> str.match( '/\(555\) 555-3300/gi/' )
null
> str.match( '/(555) 555-3300/gi/' )
null

I bet someone can answer this in 2 seconds. Googling the problem didn't help me.

Update

Also tried without the quotes:

str.match(/\(555\) 555-3300/gi/)
SyntaxError: Unexpected token )

Ultimately I'm trying to replace the phone number with a different one.

+4  A: 

Lose the quotes:

str.match(/\(480\) 945-3300/g)
John Kugelman
John's answer correctly defines a regex to match that string - though I'd point out that if you want to /exactly/ match the string, you may as well use indexOf(): if (str.indexOf("(480) 945-3300") !== -1) { /* string matches */ }
jimbojw
Tried that as well: `str.match(/\(480\) 945-3300/gi/)SyntaxError: Unexpected token )`
nnyby
stackoverflow didn't format my backlashes to escape the parens in the last comment, but i did put them in.
nnyby
With the flags it'd be `str.match(/\(480\) 945-3300/gi)` -- get rid of that trailing slash.
John Kugelman
oh, duh... thanks!
nnyby
Why doesn't it work with the RegExp() object?
nnyby
nevermind, i have to double-escape the parens: `new RegExp('\\(480\\) 555-5555')`
nnyby