JavaScript startsWith 字符串方法
在本教程中,您将学习如何使用 JavaScript 字符串的 startsWith() 方法来检查字符串是否以指定的子字符串开头。
JavaScript startsWith 方法简介
如果字符串是以指定的子字符串开头 startsWith() 方法返回 true ,否则返回 false。startsWith() 方法的语法如下所示:
String.startsWith(searchString [,position])参数
searchString是要在此字符串开头搜索的字符。position是一个可选参数,用于确定搜索的起始位置。默认为 0。
JavaScript 字符串 startsWith() 示例
假设您有字符串变量 title ,如下所示:
const title = 'Jack and Jill Went Up the Hill';以下示例使用 startsWith() 方法检查 title 是否以子字符串 'Jack' 开头:
console.log(title.startsWith('Jack'));输出:
truestartsWith() 方法以区分大小写方式匹配字符,因此以下语句返回 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结论
使用 StringstartsWith() 方法检查字符串是否指定以子字符串开头。