I expected new RegExp('\b\w{1,7}\b', "i").test('bc4rg6')
to return true since I want to test of the string "bc4rg6" is alphanumeric and has from 1 to 7 characters. But the browser is giving false. How do I fix it so that I can test for the condition stated? Thanks
Asked
Active
Viewed 35 times
0

Fred J.
- 5,759
- 10
- 57
- 106
2 Answers
0
You need to escape the backslashes in the string, because \b
is an escape sequence that turns into the backspace character.
console.log(new RegExp('\\b\\w{1,7}\\b', "i").test('bc4rg6'));
But if the regexp is a constant, you don't need to use new RegExp
, just use a RegExp literal.
console.log(/\b\w{1,7}\b/i.test('bc4rg6'))

Barmar
- 741,623
- 53
- 500
- 612
0
The RegExp
function doesn't accept a string as an argument.
Instead pass a Regular Expression
pattern with the escape slashes to indicate the start and end of the pattern.
new RegExp(/\b\w{1,7}\b/, "i").test('bc4rg6');
You can read more about the RegExp function at Mozilla.

sketchthat
- 2,678
- 2
- 13
- 22