Friday, February 10, 2012

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');
}

SsgD9
Now we've trained Javascript well!

Source

No comments:

Post a Comment

Leave your thoughts ...

---
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'.

For more information about this Firefox bug, see here.