Javascript: String starts with snippet

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!

if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (input){
return this.substring(0, input.length) === input

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

var hash = "#someAnchor";

if (hash.startsWith('#img_')) {
$('a[href="' + hash + '"]').trigger('click');

Now we've trained Javascript well!


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