Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript endsWith function not working

Tags:

javascript

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?

like image 571
nudastack Avatar asked Sep 12 '13 15:09

nudastack


People also ask

What is endsWith () in Javascript?

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.

How do you check if a string ends with a number in Javascript?

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.

What do you mean by endsWith () function?

The endswith() method returns True if the string ends with the specified value, otherwise False.


Video Answer


2 Answers

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("$"));
like image 59
vikas devde Avatar answered Oct 26 '22 23:10

vikas devde


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;
        }
    });
}
like image 34
SheetJS Avatar answered Oct 27 '22 01:10

SheetJS