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
2 Answers
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'))
Comments
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.