what is the easiest way to figure out if a string ends with a certain value?
I am just expanding on what @luca-matteis has posted but to solve the issues pointed out in the comments the code should be wrapped to make sure you are not overwriting a native implementation.
if ( !String.prototype.endsWith ) {
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
}
This is the suggested method for the Array.prototype.forEach method pointed out in the mozilla developer network
I had no luck with the match approach, but this worked:
If you have the string, "This is my string." and wanted to see if it ends with a period, do this:
var myString = "This is my string.";
var stringCheck = ".";
var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
alert(foundIt);
You can change the variable stringCheck to be any string to check for. Better still would be to throw this in your own function like this:
function DoesStringEndWith(myString, stringCheck)
{
var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
return foundIt;
}
Regular expressions
"Hello world".match(/world$/)
ES6 supports this directly:
'this is dog'.endsWith('dog') //true
you could use Regexps, like this:
str.match(/value$/)
which would return true if the string has 'value' at the end of it ($).
You can always prototype String class, this will work:
String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)}
You can find other related extensions for String class in http://www.tek-tips.com/faqs.cfm?fid=6620