1

Possible Duplicate:
Case insensitive regex in javascript

Right now I have this:

my_list.match(new RegExp("(?:^|,)"+my_name+"(?:,|$)")))

Which, given the following:

my_list = "dog, cat, boy"
my_name = "dog"

Would return true.

However if I have

my_list = "Dog,Cat,boy"

and

my_name = "boy"

The regex wouldn't match. How would I adapt in order to be able to match with case insensitive?

Community
  • 1
  • 1
Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

1 Answers1

1

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).
Tomalak
  • 332,285
  • 67
  • 532
  • 628