Javascript: String starts with snippet

0 Comments

I was surprised to find out that Javascript didn't come with such a function.

It's pretty easy to monkey patch though, it doesn't even need jQuery!

1.if (typeof String.prototype.startsWith != 'function') {
2.  String.prototype.startsWith = function (input){
3.    return this.substring(0, input.length) === input
4.  };
5.}

After that you can just use it like any other string function.

1.var hash = "#someAnchor";
2. 
3.if (hash.startsWith('#img_')) {
4.  $('a[href="' + hash + '"]').trigger('click');
5.}

SsgD9
Now we've trained Javascript well!

Source

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog