First off: Never build a regular expression from an unescaped variable. Use this function to escape all special characters first:
RegExp.quote = function(str) {
return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};
It modifies the RegExp
object, you need to include it just once. Now:
function stringContains(str, token) {
var
spaces = /^\s+|\s+$/g, // matches leading/trailing space
token = token.replace(spaces, ""), // trim the token
re = new RegExp("(?:^|,)\\s*" + RegExp.quote(token) + "\\s*(?:,|$)", "i");
return re.test(str);
}
alert( stringContains("dog, cat, boy", " Dog ") );
Note
- The
"i"
that makes the new RegExp
case-insenstive.
- The two added
\s*
that allow white-space before/after the comma.
- The fact that
"(?:^|,)\\s*"
is correct, not "(?:^|,)\s*""
(in a JS string all backslashes need to be escaped).