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

0

2 Answers 2

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'))

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.