JavaScript endsWith function not working
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?
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;
}
});
}
I have never seen an endsWith
function in JS. You can rather do an String.length and then check the last words by manually referencing each character you want to check against.
Even better would be to do a regex to find the last word in the string and then use that (Regular expression to find last word in sentence).
链接地址: http://www.djcxy.com/p/83904.html上一篇: 如何在jQuery中更改选定的项目