endsWith()
是 JavaScript 中字符串对象的一个方法,用于检查一个字符串是否以指定的子字符串结尾。以下是 endsWith()
方法的语法:
str.endsWith(searchString[, length])
searchString
: 必需。要搜索的子字符串。length
(可选):在字符串中搜索的长度。默认为字符串的长度。
endsWith()
方法返回一个布尔值,表示调用该方法的字符串是否以指定的子字符串结尾。如果是,则返回 true
;否则返回 false
。
下面是一个示例:
const str = 'Hello, world!';
console.log(str.endsWith('world!')); // 输出: true
console.log(str.endsWith('Hello')); // 输出: false
console.log(str.endsWith('world!', 7)); // 输出: false,因为只检查前7个字符
在上面的示例中,第一个 endsWith()
调用检查字符串 str
是否以子字符串 'world!'
结尾,因此返回 true
。第二个调用检查字符串 str
是否以 'Hello'
结尾,因为不是,所以返回 false
。第三个调用指定了检查的长度为 7
,因此只检查字符串的前 7
个字符,结果为 false
。