endsWith in JavaScript

前端 未结 30 1424
-上瘾入骨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:27

    if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)

    String.prototype.endsWith = function(suffix) {
        if (this[this.length - 1] == suffix) return true;
        return false;
    }
    

    or as a standalone function

    function strEndsWith(str,suffix) {
        if (str[str.length - 1] == suffix) return true;
        return false;
    }
    

提交回复
热议问题