【JS字符串】endsWith() – 确定一个字符串是否以另一个字符串结尾

JavaScript字符串1年前 (2023)发布 admin
1,648 0

在本教程中,您将学习如何使用 JavaScript String endsWith() 方法检查字符串是否以子字符串结尾。

JavaScript String endsWith() 方法介绍

如果字符串以指定字符串的字符结尾,则 endsWith() 返回 true,否则返回 false。

下面是 endsWith() 方法的语法:

String.endsWith(searchString [,length])

参数

searchString 是字符串末尾要搜索的字符。

length 是一个可选参数,用于确定要搜索的字符串的长度。 它默认为字符串的长度。

请注意,要检查字符串是否以子字符串开头,您可以使用 startsWith() 方法。

JavaScript String endsWith() 方法示例

假设您有一个名为 title 的字符串:

const title = ‘Jack and Jill Went Up the Hill’;

以下示例使用 endsWith() 方法检查标题是否以字符串“Hill”结尾:

console.log(title.endsWith(‘Hill’));

输出:

true

endsWith() 方法区分大小写匹配字符,因此,以下示例返回 false:

title.endsWith(‘hill’);

以下示例使用 endsWith() 方法,第二个参数确定要搜索的字符串的长度:

console.log(title.endsWith(‘Up’, 21));

输出:

true

把它们放在一起:

const title = ‘Jack and Jill Went Up the Hill’;

console.log(title.endsWith(‘Hill’));
console.log(title.endsWith(‘hill’));
console.log(title.endsWith(‘Up’, 21));

输出:

true
false
true

总结

使用字符串 endsWith() 方法检查字符串是否以子字。

© 版权声明

相关文章

暂无评论

暂无评论...