JavaScript String startsWith()

startsWith() 方法如果在指定字符(或字符)的开头找到匹配项,则返回 true。否则,它返回 false

示例

const message = "JavaScript is fun";

// check if message starts with Java let result = message.startsWith("Java");
console.log(result); // true
// check if message starts with Script result = message.startsWith("Script");
console.log(result); // false

startsWith() 语法

startsWith() 方法的语法是

str.startsWith(searchString, position)

其中,str 是一个字符串。


startsWith() 参数

startsWith() 方法接受

  • searchString - 要在 str 开头搜索的字符。
  • position (可选) - 在 str 中开始搜索 searchString 的位置。默认值为 0

startsWith() 返回值

  • 如果给定的字符在字符串开头找到,则返回 true
  • 如果给定的字符在字符串开头未找到,则返回 false

注意startsWith() 方法区分大小写。


示例:使用 startsWith() 方法

sentence = "Java is to JavaScript what Car is to Carpet.";

let check = sentence.startsWith("Java");
console.log(check); // true let check1 = sentence.startsWith("Java is"); console.log(check1); // true // case sensitive
let check2 = sentence.startsWith("JavaScript");
console.log(check2); // false // second argument specifies the starting position
let check3 = sentence.startsWith("JavaScript", 11);
console.log(check3); // true

输出

true
true
false
true

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战