Lau Lau - 1 year ago 127
Javascript Question

RegExp case insensitive search for whole word with variable

I have an object with strings properties I want to compare to multiple user inputs using case insensitivity. My goal is to match input strings to object strings to increment the associated value by 1 (if it's a match).

var objArr = [
{"O": 0},
{"foo": 0},
{"faa": 0},
{"A": 0}

Everything is working smoothly except for the case insensitivity. The RegExp method I used just looks for one letter instead of the whole word. I'm probably not using the right syntax, but I can't find results on google which explain the
flag along with a variable.
My closest try was :

var re = new RegExp(b, "i"); //problem here
if (allinputs[i].value.match(re)) { //and here

This code indeed allows case insensitivity but it doesn't look for the whole object property string and stops for letters. For exemple typing "foo" will result in a match to "O" because it contains the letter "O", and the property "O" is before "foo". Accordingly, typing "faa" matches to "faa" and not "A", because "faa" is before "A" in the objects array. Strings that don't exist in my object like "asfo" will still be matched to "O" because of the one common letter.

Is there a way to search for the whole property string with case insensivity using the
/i flag
? I want to avoid using .toUpperCase() or .toLowerCase() methods if possible.

Fiddle here :

Thanks for your help

Answer Source

To check that a regex matches the entire string, you can use the assert beginning character (^) and assert end ($).

For example, hello matches e but not ^e$.

For your code, just prepend ^ to the regex and append $:

var re = new RegExp("^" + b + "$", "i");


Edit: Some characters have special meanings in regexes (^, $, \, ., *, etc). If you need to use any of these characters, they should be escaped with a \. To do this, you can use this simple replace:

str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

So, your regex will end up being

new RegExp("^" + b.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "$", "i");

See this question for more about escaping a regex.

You could also just convert the two strings to lowercase and then compare them directly. This will allow you to use special characters as well.

if (stringA.toLowerCase() == stringB.toLowerCase())) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download