9nfu0a
Last Updated: February 25, 2016
·
2.355K
· mnbbrown
768e05071b05a6fa5c396fa129c6f013

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

Say Thanks
Respond