endsWith in JavaScript

前端 未结 30 1541
-上瘾入骨i
-上瘾入骨i 2020-11-22 05:41

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

Example: I have a string

var str = \"mystring#\";

I wa

30条回答
  •  爱一瞬间的悲伤
    2020-11-22 06:02

    return this.lastIndexOf(str) + str.length == this.length;
    

    does not work in the case where original string length is one less than search string length and the search string is not found:

    lastIndexOf returns -1, then you add search string length and you are left with the original string's length.

    A possible fix is

    return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
    

提交回复
热议问题