JavaScript String endsWith() 方法用于确定字符串是否以指定字符 (substring) 结尾。如果在字符串末尾找到指定的子字符串字符,则返回布尔值 'true';否则,它返回 'false'。
如果 searchString 参数是正则表达式,则此方法将引发 TypeError 异常。它区分大小写,因此它将“Hello”和“HELLO”视为不同的字符串。
语法
以下是 JavaScript String endsWith() 方法的语法 -
参数
该方法接受两个参数:“searchString”和“endPosition”。endPosition 参数是可选的,用于指定搜索结束的字符串中的索引(位置)。
- searchString − 要在字符串末尾搜索的字符。
- endPosition (可选) − 字符串中搜索结束的位置。
返回值
如果字符串以指定的子字符串结尾,则此方法返回 true,否则返回 false。
示例 1
如果字符串以指定的字符结尾,则返回 true。
在此示例中,我们使用 JavaScript String endsWith() 方法来检查字符串 “QikepuCom” 是否以指定的子字符串 “Com” 结尾。
输出
上面的程序返回 'true'。
Search string: Com
Is string 'QikepuCom' ends with 'Com'or not? true
示例 2
如果字符串不以指定字符结尾,则返回 false。
这是 JavaScript String endsWith() 方法的另一个示例。在此示例中,我们使用该方法判断字符串 “Hello World” 是否以指定的字符串 “Word” 结尾。
输出
执行上述程序后,返回 'false'。
Search string: Word
Is string 'Hello World' ends with 'Word' or not? false
示例 3
如果我们将 endPosition 参数值传递为 15,它会检查以索引 15 结尾的字符串是否以指定的子字符串结尾,并忽略字符串的其余部分。如果子字符串与 searchString 的末尾匹配(直到索引 15),则返回 true;否则,它将返回 false。
输出
执行上述程序后,它将返回 'false'。
End position: 15
Search string: Tuto
String actual length: 21
Is string 'Welcome to Qikepu Com'(upto length 15) ends with 'Tuto' or not? false
示例 4
JavaScript String endsWith() 方法要求 searchString 参数为字符串。如果它是正则表达式,则会引发 'TypeError' 异常。
输出
上述程序会引发 'TypeError' 异常。
Search string: /ab+c/
TypeError: First argument to String.prototype.endsWith must not be a regular expression