2
nameArray = new Array("Bob", "Ben", "Don");
for (i = 0; i < nameArray.length; i++) {
re = new RegExp("\b(" + nameArray[i] + ")\b");
checkWord = re.test("Bob");
if (checkWord) {
    alert("true");
} else {
    alert("false");
}
}​

It returned false 3 times. It should return true the first time the loop runs. I dont know what's my error. Can anyone help? Thanks.

3 Answers 3

3

You must use double escape since you are writing a string:

new RegExp("\\b(" + nameArray[i] + ")\\b");
Sign up to request clarification or add additional context in comments.

1 Comment

@raina77ow Actually \b will be interpreted as a backspace character and not the b character.
1

You might want to look into what the pipe (|) means in regular expressions. No loop required:

var nameArray = new Array("Bob", "Ben", "Don");
var nameExpression = nameArray.join('|');
var re = new RegExp('\\b(' + nameExpression + ')\\b');
var checkWord = re.test('A string containing the word Bob in it.');
if (checkWord)
  console.log('+');
else 
  console.log('-');

Also, you are not declaring your variables. You should declare variables with var or else you will generate global variables which is dangerous and considered bad style.

Comments

0

I think a regex like this will work

re = new RegExp("^" + nameArray[i] + "$");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.