Last Updated: February 25, 2016
·
3.032K
· mnbbrown

Javascript string endsWith()

The following adds an endsWith method to any string. Requires underscore.js.

if (typeof String.prototype.endsWith === 'undefined') {
    String.prototype.endsWith = function(suffix) {
        if (typeof suffix === 'String') {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        }else if(suffix instanceof Array){
            return _.find(suffix, function(value){
                console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
                return this.indexOf(value, this.length - value.length) !== -1;
            }, this);
        }
    };
}

It takes both an Array or a string as an argument. Use cases:

 if ( "image.iso".endsWith([".iso",".zip",".tar.gz",".tgz","tar"])){
       // Do something
 }

if ( "Hello World".endsWith("World")){
       // Do something
 }

References: http://stackoverflow.com/questions/280634/endswith-in-javascript