javascript tutorial - [Solved-5 Solutions] endsWith in JavaScript - javascript - java script - javascript array



Problem:

How can I check if a string ends with a particular character in JavaScript?

Solution 1:

var str = "mystring#";
click below button to copy the code. By JavaScript tutorial team

Solution 2:

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

click below button to copy the code. By JavaScript tutorial team

Solution 3:

function makeSuffixRegExp(suffix, caseInsensitive) {
  return new RegExp(
      String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
      caseInsensitive ? "i" : "");
}
click below button to copy the code. By JavaScript tutorial team

and then we can use it like this

makeSuffixRegExp("a[complicated]*suffix*").test(str)
click below button to copy the code. By JavaScript tutorial team

Solution 4:

endsWith implementation:

String.prototype.endsWith = function (s) {
  return this.length >= s.length && this.substr(this.length - s.length) == s;
}

click below button to copy the code. By JavaScript tutorial team

Solution 5:

String.prototype.endsWith = function(str)
{
    var lastIndex = this.lastIndexOf(str);
    return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - endsWith in JavaScript