I have a web application. In one of the pages, I go all over the HTML element IDs wether one of them ends with a specified string or not. Every JS functions work on the page but "endsWith" function doesn't work. I really didn't understand the matter. Can anyone help?
var str = "To be, or not to be, that is the question.";
alert(str.endsWith("question."));
The above simple JS code doesn't work at all?
The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.
To check if a string ends with a number, call the test() method on a regular expression that matches one or more numbers at the end a string. The test method returns true if the regular expression is matched in the string and false otherwise.
The endswith() method returns True if the string ends with the specified value, otherwise False.
As said in this post http://rickyrosario.com/blog/javascript-startswith-and-endswith-implementation-for-strings/
var str = "To be, or not to be, that is the question.";
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
alert(strEndsWith(str,"question."));
this will return true if it ends with provided suffix.
JSFIDDLE
EDIT
There is a similar question asked before check it here
the answer says
var str = "To be, or not to be, that is the question$";
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
alert(str.endsWith("$"));
ES5 has no endsWith
function (or, for that matter, startsWith
). You can roll your own, like this version from MDN:
if (!String.prototype.endsWith) {
Object.defineProperty(String.prototype, 'endsWith', {
enumerable: false,
configurable: false,
writable: false,
value: function (searchString, position) {
position = position || this.length;
position = position - searchString.length;
var lastIndex = this.lastIndexOf(searchString);
return lastIndex !== -1 && lastIndex === position;
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With