The following is a quick JavaScript function which can determine if a string ends with a substring:


String.prototype.endsWith = function(str, ignoreCase) {
  return (ignoreCase ? this.toUpperCase() : this).slice(-str.length)
    == (ignoreCase ? str.toUpperCase() : str);
};

The above function is a function that, once defined, will exist for every string. The first parameter, which is the string to be found, is required. The second parameter, which is a boolean specifying to ignore casing if true, is not required and defaults to false. Here are some examples of how to use the above function:


alert("Chris".endsWith("is")); // true
alert("Chris".endsWith("Ris")); // false
alert("Chris".endsWith("Ris", true)); // true

Leave a Reply

Your email address will not be published. Required fields are marked *