7

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
nudastack
  • 155
  • 1
  • 5
  • 18
  • 1
    How exactly is this problem related to JSF? Are you implying that when you remove all the JSF stuff (and use a plain vanilla `.html` page), that this problem then disappears? This is unbelieveable as JSF actually doesn't run in webbrowser, but in webserver. I'll edit your question to get rid of irrelevant JSF noise. As to your problem, carefully read browser compatibility list of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith For the future questions, please naildown the problem more carefully. – BalusC Sep 12 '13 at 15:28
  • Calm down @BalusC! JSF has a function called `endsWith`. It's obvious that the questioner has got confused, see http://myfaces.apache.org/core20/myfaces-impl/tlddoc-facelets/fn/endsWith.fn.html . It was indeed helpful to include JSF in the question so we can say that they have confused the functionality of JSF and JavaScript. – Joe Sep 12 '13 at 15:35
  • @Joe: Uh, EL doesn't run in JS context at all. Thank you for the laugh of the day though :) For future comments it's perhaps better to refrain from commenting on subjects you know nothing about. – BalusC Sep 12 '13 at 15:39
  • Sorry, for the inconvenience. JS functions are inside html tag, not inside JSF page. I wanted to be more specific :) "endsWith" function is not supported for Chrome. What should I use instead? – nudastack Sep 12 '13 at 15:40
  • 1
    @BalusC - I was saying that nudastack was confused, not me, and that he was giving us an opportunity to help him/her rather than just laugh at him. Stop and think for a minute before replying. – Joe Sep 12 '13 at 15:43
  • @Joe: Uh, I didn't laugh at him. – BalusC Sep 12 '13 at 15:45
  • 1
    I was saying that including the JSF tag is a hint that the questioner mixed up JSF and JS. I do know what I'm talking about. You misread my comment, by mistake or on purpose because of your attitude. I'm not going to expend any more effort finding out which. – Joe Sep 12 '13 at 15:50
  • @Joe: Sorry, for my harshness (I'm just stating the truth), but code posted so far is very definitely not JSF. JSF is in the context of this question merely a HTML/CSS/JS code producer :) The EL function which you ridiculously referenced as a probable mixup has a completely different purpose than running in JS context. If you go this path in another languages, you're basically saying the same as "Hey, but, but, he probably confused with PHP's, or Java's or Python's `endsWith()`!" (if any) which isn't making any sense in this context. – BalusC Sep 12 '13 at 15:54
  • 1
    It's clear that we are having communication problems, and it's not worth the effort trying to fix them. Either I am struggling to write English clearly or you are struggling to comprehend it accurately. I am not saying that the above code is JSF. I am not saying that there is an `endsWith` function is JavaScript. I am not saying that you can call JSF functions from JS. I am not mixing up their respective execution contexts. I *am* trying to make some effort to understand the question rather than insult people left right and centre. I *am* here to help. I am not continuing this conversation. – Joe Sep 12 '13 at 16:00
  • @Joe: In contrary, your command of English is very clear :) Have a good day. Don't forget to take a break :) – BalusC Sep 12 '13 at 16:02

4 Answers4

9

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("$"));
Community
  • 1
  • 1
vikas devde
  • 11,691
  • 10
  • 35
  • 42
  • Test your solution with the suffix "$". It would be treated as a regular expression, so even the string `"To be, or not to be, that is the question."` would match. – SheetJS Sep 12 '13 at 15:42
  • depends on the purpose of use, else you can add check for `$` – vikas devde Sep 12 '13 at 15:47
5

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;
        }
    });
}
SheetJS
  • 22,470
  • 12
  • 65
  • 75
  • It's strange that they would use `lastIndexOf` rather than just `substring`. – Dan Tao Sep 12 '13 at 15:36
  • What if the needle appeared twice in the string? Would `substring` work in that situation? – Joe Sep 12 '13 at 15:37
  • @DanTao that's due to the semantics of their version of endsWith. The second argument (position) is described as "Search within this string as if this string were only this long; defaults to this string's actual length, clamped within the range established by this string's length.", which requires a second check anyway. – SheetJS Sep 12 '13 at 15:38
  • @Joe you would do something like `str.substring(str.length - needle.length)`, obviating that problem – SheetJS Sep 12 '13 at 15:39
  • enumerable, configurable and writable can be omitted since they are all false by default [see here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) – Jan Turoň Sep 12 '13 at 15:45
  • @Nirk: But you could handle that logic with `substring` as well. Obviously it's just a demonstration, but my point is that using `lastIndexOf` potentially searches the whole string when all you really need to do is check a specific section of it (the end, from a given position) and see if it matches the needle. So basically their implementation is suboptimal. But again, it's just an example so who cares, really. – Dan Tao Sep 12 '13 at 15:46
  • @DanTao I'm not saying you can't do it with substring (and in fact, I gave an example of it), but doing it this way isn't wrong either. – SheetJS Sep 12 '13 at 15:47
0

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).

Community
  • 1
  • 1
J D
  • 1,768
  • 2
  • 18
  • 20
0

I found the endsWith() function available in Chrome console, but oddly, not defined when debugging in VS Code (with Chrome). You can try editing the snippet below by deleting the polyfill to see if your browser supports it.

This is a quote from MDN Developer Docs for String.prototype.endsWith():

String.prototype.endsWith()

This method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet. However, you can polyfill String.prototype.endsWith() with the following snippet:

// If string.endsWith() isn't defined, Polyfill it.
if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(search, this_len) {
    if (this_len === undefined || this_len > this.length) {
      this_len = this.length;
    }
    return this.substring(this_len - search.length, this_len) === search;
  };
}

// Use it.
const myString = "Mayberry";
const result = myString.endsWith("berry") ? 'Yes' : 'Nope';
document.body.append('A. ' + result);
Q. Does Mayberry end with "berry"?<br>
Benson
  • 4,181
  • 2
  • 26
  • 44