endsWith in JavaScript

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

    /#$/.test(str)
    

    will work on all browsers, doesn't require monkey patching String, and doesn't require scanning the entire string as lastIndexOf does when there is no match.

    If you want to match a constant string that might contain regular expression special characters, such as '$', then you can use the following:

    function makeSuffixRegExp(suffix, caseInsensitive) {
      return new RegExp(
          String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
          caseInsensitive ? "i" : "");
    }
    

    and then you can use it like this

    makeSuffixRegExp("a[complicated]*suffix*").test(str)
    

提交回复
热议问题