0

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

Fred J.
  • 5,080
  • 8
  • 50
  • 95

2 Answers2

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
  • 669,327
  • 51
  • 454
  • 560
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,558
  • 2
  • 12
  • 22