How can I check if a string ends with a particular character in JavaScript?
Example: I have a string
var str = \"mystring#\";
I wa
This builds on @charkit's accepted answer allowing either an Array of strings, or string to passed in as an argument.
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);
}
};
}
This requires underscorejs - but can probably be adjusted to remove the underscore dependency.
all of them are very useful examples. Adding String.prototype.endsWith = function(str)
will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.
I found a better solution than mine. Thanks every one.
If you're using lodash:
_.endsWith('abc', 'c'); // true
If not using lodash, you can borrow from its source.
@chakrit's accepted answer is a solid way to do it yourself. If, however, you're looking for a packaged solution, I recommend taking a look at underscore.string, as @mlunoe pointed out. Using underscore.string, the code would be:
function endsWithHash(str) {
return _.str.endsWith(str, '#');
}
Just another quick alternative that worked like a charm for me, using regex:
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
function strEndsWith(str,suffix) {
var reguex= new RegExp(suffix+'$');
if (str.match(reguex)!=null)
return true;
return false;
}