Reputation: 337
I'm trying to loop through an array of words that are not allowed. However I'm trying to match the word exactly: for example I would want to do something if it matched "cat" not "catering". So I'm trying to test to see whether there are spaces before and after the word, to see if it's a single word and not part of another.
Here's my attempt:
var badWords = [
"cat",
"catering",
"cattle"
];
var string = "";
for (j=0;j<badWords.length;j++) {
var regex = "/\s" + badWords[j] + "\s/";
if string.search(regex)) {
alert("works");
}
}
Upvotes: 0
Views: 38
Reputation: 6203
var badWords = [
"cat",
"catering",
"cattle"
];
var string = "cat";
for (var j=0;j<badWords.length;j++) {
var patt = new RegExp("(^|\\b)" + badWords[j] + "(\\b|$)");
if(patt.test(string)) {
console.log("works");
}
}
Upvotes: 2