js startWith

在 JavaScript 中,startsWith() 方法用于检查字符串是否以指定的字符序列开头。若字符串以指定的字符序列开头,则返回 true,否则返回 false

语法:

str.startsWith(searchString[, position])
  • searchString:要检查的字符序列,作为 str 开头的一部分。
  • position(可选):开始搜索的起始位置,默认是 0

示例:

let str = "Hello, world!";

console.log(str.startsWith("Hello"));  // true
console.log(str.startsWith("world"));  // false
console.log(str.startsWith("world", 7)); // true (从索引 7 开始检查)

解释:

  • str.startsWith("Hello") 返回 true,因为字符串确实是以 "Hello" 开头的。
  • str.startsWith("world") 返回 false,因为字符串不是以 "world" 开头的。
  • str.startsWith("world", 7) 返回 true,因为它从位置 7 开始检查,恰好在这里 "world" 开始。
posted @ 2025-04-18 16:44  盘思动  阅读(51)  评论(0)    收藏  举报