SiteKickr Web Development

A shorthand substring search function for JavaScript

Being a full stack developer, I’ve grown to love certain things about many different languages. The problem with that, however, is that I often find it annoying when doing something in one language is so much easier in another language.

Just today, I finally became annoyed enough with the JavaScript indexOf function that I decided to write a quick function for the String prototype.

If you’ve used Python for anything more than 5 minutes, you’ll instantly fall in love with the “in” syntax, and how flexible it is across strings or lists, i.e.

if 'bob' in 'bobcat'

After using that super-simple syntax on the back-end, you get a little annoyed when you have to write dozens of string search functions in JavaScript like so:

if ('bobcat'.indexOf('bob') !== -1)

Of course, a single conditional like that is nothing too daunting. But, when you have to run dozens of comparisons, it gets a little monotonous. Not to mention, the code looks a little sloppy.

So, to get past this, I just threw together a quick String prototype function:

String.prototype.in = function (needle, case_sensitive) {
   if (typeof case_sensitive === 'undefined')
      case_sensitive = false;

   if (case_sensitive)
      return (needle.indexOf(this) !== -1);
   else
      return (needle.toLowerCase().indexOf(this.toLowerCase()) !== -1);
}

Now, I can feel a little happier as I write my string search functions like so:

if ('bob'.in('bobcat'))

 

So to return to that whole bit about loving different features of different languages, it goes without saying that I absolutely love the Prototype concept in JavaScript!