0

I’ve used indexOf to search for a term within a text (both are strings), like so:

if (text.indexOf(term) > -1) { …

However, I would like the search to not be case sensitive. I’ve tested with performing .toLowerCase() on both strings, but the performance penalty of doing that is significant (I’m searching on an array of texts with thousands of elements). I’m therefore considering switching to .search(), like so:

var re = new RegExp(term, 'i');

// and then
if (text.search(re) > -1) { …

Is this approach feasible? How can I make sure that the term is treated “literally” in this scenario, i.e. that certain characters in term aren’t interpreted as special characters?

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • 1
    I would suggest to use `test` instead of `search` – Tushar Oct 13 '15 at 04:14
  • 1
    This is how you escape regex metacharacters: [Is there a RegExp.escape function in Javascript?](http://stackoverflow.com/q/3561493/5290909) – Mariano Oct 13 '15 at 04:20
  • @Tushar I’ve tested (via `console.time/timeEnd`) and there seems to be no difference in performance. (`test` is still better for my scenario though) – Šime Vidas Oct 13 '15 at 04:20
  • @Mariano Aha, so “escaping metacharacters” means they become literals in the regex. It seems to work on this simple example: https://jsbin.com/foradi/edit?js,console – Šime Vidas Oct 13 '15 at 04:30
  • That's exactly what it means. – Mariano Oct 13 '15 at 04:33
  • if it's slow, you can make such a task ~25 times faster by using 26 different arrays, a-z by first letter, then looking only in the related sub-set array to find matches... ok, if these are real words, it will probably only be 10X faster since RSTLNE will hog a lot of action... same RAM though... – dandavis Oct 13 '15 at 04:37

0 Answers0