Just a quick TIL post this week. Don’t worry, I’ve got another rambler lined up for next week involving converting data for display then to another form for sorting, then back again- what a ride!
Side note: we are only searching through content that’s already been loaded from the server, so it’s nice and fast, but if we were hitting the server on search, there’s a great rxJs operator- debounceTime. Pass it a number and it will wait that period (in milliseconds) after your event before actually firing the action. Basically, chain it to your subscription before your .subscribe operator and you’re good to go! Super simple client side rate limiting!
Back on topic: the search worked, except when I tested with a special character. The dollar symbol (“$”) in this case. The grid had a column where this symbol would regularly appear in the text, but each time I tried to search for “MM$vx”, I would get no results- even if that text appeared in my grid.
Turns out- string.search doesn’t appear to work with some (or maybe all?) special characters inside a string. I did a quick Google search as to why, but didn’t come up with any specific reasons for this so I might be totally wrong, but I did test this out in an awesome little tool at repl.it – it’s great for quickly checking if code works like you think it should.
const test = 'U$11M'.toLowerCase();
const nope = test.search('u$11m');
const works = test.includes('u$11m');
console.log(nope); // -1 not found
console.log(works); // true
console.log(test, 'u$11m', test === 'u$11m'); //same string
Interactive version at https://repl.it/H5AJ/2
You’ll see the solution in that snippet too- switch to string.includes. That method doesn’t have any issues with any symbol I tested so far, so that’s what we’re using now. I’ll be honest- I didn’t even know string had an “includes” method- that’s why we were using search!
One thing to note: string.includes returns boolean, while string.search returns the index of your substring, so be sure to do your checks for the proper thing (particularly when using the all powerful === check).