How can I check if a string ends with a particular character in JavaScript?
Example: I have a string
var str = \"mystring#\";
I wa
return this.lastIndexOf(str) + str.length == this.length;
does not work in the case where original string length is one less than search string length and the search string is not found:
lastIndexOf returns -1, then you add search string length and you are left with the original string's length.
A possible fix is
return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
For coffeescript
String::endsWith = (suffix) ->
-1 != @indexOf suffix, @length - suffix.length
function check(str)
{
var lastIndex = str.lastIndexOf('/');
return (lastIndex != -1) && (lastIndex == (str.length - 1));
}
Its been many years for this question. Let me add an important update for the users who wants to use the most voted chakrit's answer.
'endsWith' functions is already added to JavaScript as part of ECMAScript 6 (experimental technology)
Refer it here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
Hence it is highly recommended to add check for the existence of native implementation as mentioned in the answer.
After all those long tally of answers, i found this piece of code simple and easy to understand!
function end(str, target) {
return str.substr(-target.length) == target;
}
Do not use regular expressions. They are slow even in fast languages. Just write a function that checks the end of a string. This library has nice examples: groundjs/util.js. Be careful adding a function to String.prototype. This code has nice examples of how to do it: groundjs/prototype.js In general, this is a nice language-level library: groundjs You can also take a look at lodash