DEV Community

String.prototype.search(): a method I wish I knew about a long time ago

Ken Bellows on June 23, 2020

tl;dr: String.prototype.search() is basically .indexOf() but with regexes. It's been supported in every browser since IE 4, but ES6 made it more p...
Collapse
 
sirseanofloxley profile image
Sean Allin Newell

Hidden gem 💎 for sure, thanks! 🚀

Collapse
 
gottz profile image
Jan-Stefan Janetzky

if ye want another exciting fact about browser js:

element.append is a thing and accepts multiple dom elements.

(me being one of the people who started with js when netscape had that nice brushed aluminium theme literally missed the addition of this neat little function)

Collapse
 
z2lai profile image
z2lai

Wow, I learnt way more than just the search method. What an article!

Collapse
 
ben profile image
Ben Halpern

TIL me too!

Collapse
 
kenbellows profile image
Ken Bellows

Right??

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Symbol.search huh - I do like that syntax.

Collapse
 
skaytech profile image
skaytech

Thanks for sharing Ken. It's very useful. Learnt something new today :-)

Collapse
 
cainrus profile image
cainrus

So you can make extra wrapper for exec / match method to simplify code in the userland.

Collapse
 
kenbellows profile image
Ken Bellows

Yeah, you definitely could do it that way, utilize myregex.exec() or myregex.match() inside of your method. Could be a nice way to encapsulate some ugly, repetitive logic, especially if you did this sort of thing all the time and wanted to write a factory function to take a regex and generate these search objects. Again, I don't really know if it's any cleaner in the end than just defining a findIndex(str, pattern) function, especially if not everyone reading your code will know about these symbols and understand how you're using them, but when I have the choice, I usually prefer dealing with native methods like str.search(pattern), since they have well-defined behavior and I know what to expect. Personal preference, I guess

Collapse
 
maeve54729273 profile image
maeve

Great to know ! Thanks for sharing :)

Collapse
 
quyethn2 profile image
quyethn2

wow, thank you!
I dont know about "data-*" in html, when do use it?

Collapse
 
kenbellows profile image
Ken Bellows

Hey! That's a bit off-topic for this article, so I don't want to go over it in this comments section, but I love talking about that sort of thing, so DM me if you want to talk about it!

Collapse
 
johnylab profile image
João Ferreira

OMG! Data lake in JS. Yeah!