endsWith in JavaScript

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

    This builds on @charkit's accepted answer allowing either an Array of strings, or string to passed in as an argument.

    if (typeof String.prototype.endsWith === 'undefined') {
        String.prototype.endsWith = function(suffix) {
            if (typeof suffix === 'String') {
                return this.indexOf(suffix, this.length - suffix.length) !== -1;
            }else if(suffix instanceof Array){
                return _.find(suffix, function(value){
                    console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
                    return this.indexOf(value, this.length - value.length) !== -1;
                }, this);
            }
        };
    }
    

    This requires underscorejs - but can probably be adjusted to remove the underscore dependency.

提交回复
热议问题