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 is the implementation of endsWith :
String.prototype.endsWith = function (str) {
return this.length >= str.length && this.substr(this.length - str.length) == str;
}
From developer.mozilla.org String.prototype.endsWith()
The endsWith()
method determines whether a string ends with the characters of another string, returning true or false as appropriate.
str.endsWith(searchString [, position]);
searchString : The characters to be searched for at the end of this string.
position : Search within this string as if this string were only this long; defaults to this string's actual length, clamped within the range established by this string's length.
This method lets you determine whether or not a string ends with another string.
var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") ); // true
alert( str.endsWith("to be") ); // false
alert( str.endsWith("to be", 19) ); // true
ECMAScript Language Specification 6th Edition (ECMA-262)
if( "mystring#".substr(-1) === "#" ) {}
Didn't see apporach with slice
method. So i'm just leave it here:
function endsWith(str, suffix) {
return str.slice(-suffix.length) === suffix
}
if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)
String.prototype.endsWith = function(suffix) {
if (this[this.length - 1] == suffix) return true;
return false;
}
or as a standalone function
function strEndsWith(str,suffix) {
if (str[str.length - 1] == suffix) return true;
return false;
}
So many things for such a small problem, just use this Regular Expression
var str = "mystring#";
var regex = /^.*#$/
if (regex.test(str)){
//if it has a trailing '#'
}