endsWith in JavaScript

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

    if(typeof String.prototype.endsWith !== "function") {
        /**
         * String.prototype.endsWith
         * Check if given string locate at the end of current string
         * @param {string} substring substring to locate in the current string.
         * @param {number=} position end the endsWith check at that position
         * @return {boolean}
         *
         * @edition ECMA-262 6th Edition, 15.5.4.23
         */
        String.prototype.endsWith = function(substring, position) {
            substring = String(substring);
    
            var subLen = substring.length | 0;
    
            if( !subLen )return true;//Empty string
    
            var strLen = this.length;
    
            if( position === void 0 )position = strLen;
            else position = position | 0;
    
            if( position < 1 )return false;
    
            var fromIndex = (strLen < position ? strLen : position) - subLen;
    
            return (fromIndex >= 0 || subLen === -fromIndex)
                && (
                    position === 0
                    // if position not at the and of the string, we can optimise search substring
                    //  by checking first symbol of substring exists in search position in current string
                    || this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
                )
                && this.indexOf(substring, fromIndex) === fromIndex
            ;
        };
    }
    

    Benefits:

    • This version is not just re-using indexOf.
    • Greatest performance on long strings. Here is a speed test http://jsperf.com/starts-ends-with/4
    • Fully compatible with ecmascript specification. It passes the tests

提交回复
热议问题