XTA
June 23, 2017, 6:37pm
1
Hey guys,
I’m trying to make a case insensitive query against my collection. This is how my query looks like:
const artist = Artists.findOne({name: new RegExp(name, 'i')});
For most of the cases, this works fine. But it fails if the name includes some special chars, f.e.:
const name = "Big Sean & Jhene Aiko (Twenty88)";
In this case I wouldn’t get the artist document. Is there any way to handle this easily?
() are special characters in regular expressions
> const name = "Big Sean & Jhene Aiko (Twenty88)";
> const r1 = new RegExp(/Big Sean & Jhene Aiko (Twenty88)/,'i');
> name.match(r1)
< null
> r2 = new RegExp(/Big Sean & Jhene Aiko \(Twenty88\)/,'i')
> name.match(r2)
< ["Big Sean & Jhene Aiko (Twenty88)"] (1)
Interestingly the following RegExp to escape the () works in Firefox and Chrome, but not in Safari
Firefox, Chrome
> name = "Big Sean & Jhene Aiko (Twenty88)";name.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
< "Big Sean & Jhene Aiko \(Twenty88\)"
Safari
> name = "Big Sean & Jhene Aiko (Twenty88)";name.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
< "Big Sean & Jhene Aiko \\(Twenty88\\)"
XTA
June 24, 2017, 11:12am
4
Ah okay, so I need to escape all special chars for RegEx. I’m just wondering if creating a text index and then do a case insensitive query would be the better way to handle this?
Yeah I’m guessing that’s probably going to have much better performance.