Word boundary won't match the beginning or end in Javascript
Asked Answered
T

2

7

I'm getting unexpected results with this code:

'foo'.match(new RegExp('\bfoo\b')); // Returns null

Why is this returning null while this one returns "foo"?

'foo'.match(new RegExp('foo')); // Returns "foo"

Doesn't a word boundary marker match the beginning and end as well?

EDIT: I need the regular expression itself to be a string because I am injecting variables into it.

Turaco answered 17/2, 2011 at 2:57 Comment(0)
P
15

Escape the backslashes

'foo'.match(new RegExp('\\bfoo\\b'));
Po answered 17/2, 2011 at 3:7 Comment(1)
Do you know why the backslash for this needs to be escaped but it doesn't for something like getting a forward slashEstabrook
K
-2

Don't wrap it in quotes... instead, do this:-

'foo'.match(new RegExp(/\bfoo\b/))
Keelboat answered 17/2, 2011 at 3:4 Comment(2)
I need it to be a string because I'm dropping in values.Turaco
@mattalexx: That really should be part of your question if you want it to persist here and be useful to others.Eagre

© 2022 - 2024 — McMap. All rights reserved.