【JS字符串】startsWith() – 检查一个字符串是否以另一个字符串开头

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

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

JavaScript startsWith()方法介绍

如果字符串以子字符串开头,则 startsWith() 返回 true,否则返回 false。

下面显示了 startsWith() 方法的语法:

String.startsWith(searchString [,position])

参数
searchString 是要在此字符串开头搜索的字符。
position 是一个可选参数,用于确定搜索 searchString 的起始位置。 它默认为 0。

JavaScript String startsWith() 例子

假设您有一个名为 title 的字符串,如下所示:

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

以下示例使用 startsWith() 方法检查标题是否以字符串“Jack”开头:

console.log(title.startsWith(‘Jack’));

输出:

true

startsWith() 方法区分大小写匹配字符,因此以下语句返回 false:

title.startsWith(‘jack’);

此示例使用startsWith()带有第二个参数的方法来确定开始搜索的起始位置:

console.log(title.startsWith(‘Jill’, 9));

输出:

true

把它们放在一起:

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

console.log(title.startsWith(‘Jack’));
console.log(title.startsWith(‘jack’));
console.log(title.startsWith(‘Jill’, 9));

输出:

true
false
true

总结

使用 String startsWith() 方法可以检查字符串是否以子字符串开头。

© 版权声明

相关文章

暂无评论

暂无评论...