endsWith in JavaScript

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

    This version avoids creating a substring, and doesn't use regular expressions (some regex answers here will work; others are broken):

    String.prototype.endsWith = function(str)
    {
        var lastIndex = this.lastIndexOf(str);
        return (lastIndex !== -1) && (lastIndex + str.length === this.length);
    }
    

    If performance is important to you, it would be worth testing whether lastIndexOf is actually faster than creating a substring or not. (It may well depend on the JS engine you're using...) It may well be faster in the matching case, and when the string is small - but when the string is huge it needs to look back through the whole thing even though we don't really care :(

    For checking a single character, finding the length and then using charAt is probably the best way.

提交回复
热议问题