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!

Tags:

3 Comments

  1. The great post. One tip: You will can remove the else conditional and return directly the last value or use the regex for test the substring. 😉

    1. I think the “else” makes the code a little more readable, but not by that much 😉

      I always assume that RegEx testing is slower than basic string searching, but maybe I shouldn’t!

      1. i aggred to you which regexp may be slower, but remove is else, in my opinion is the fast and readable and follows the best clean code practice. But i think you post is great.

Leave a Reply

Your email address will not be published. Required fields are marked *