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
Written by Matthew Brown
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#String
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#