JavaScript indexOf to ignore Case

You can use regex with a case-insensitive modifier - admittedly not necessarily as fast as indexOf.

var noPic = largeSrc.search(/nopic/i);

Note that if the search string is from user input you'll need to escape the special regexp characters.

Here's what it would look like:

var search = getUserInput();

/* case-insensitive search takes around 2 times more than simple indexOf() */
var regex = RegExp(search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i");

var noPic = testString.search(regex);

See the updated jsperf: http://jsperf.com/regex-vs-tolowercase-then-regex/4

footnote: regexp escaping from https://stackoverflow.com/a/3561711/1333402


No, there is no case-insensitive way to call that function. Perhaps the reason your second example doesn't work is because you are missing a call to the text() function.

Try this:

var search = "nopic";
var noPic = largeSrc.text().toLowerCase().indexOf(search.toLowerCase());

Tags:

Javascript