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?

0

1 Answer 1

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).
Sign up to request clarification or add additional context in comments.

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.