📜  JavaScript String startsWith() 方法(1)

📅  最后修改于: 2023-12-03 14:42:27.189000             🧑  作者: Mango

JavaScript String startsWith() 方法

介绍

startsWith() 方法是 JavaScript 字符串对象的一个方法,用于检查一个字符串是否以指定的子字符串开头。它返回一个布尔值,即如果字符串以指定的子字符串开头,则返回 true,否则返回 false

语法
str.startsWith(searchString[, position])
  • searchString:要搜索的子字符串。
  • position(可选):指定搜索的起始位置,默认为 0。
返回值

startsWith() 方法返回一个布尔值。如果字符串以指定的子字符串开头,则返回 true,否则返回 false

示例
const str = 'Hello, world!';

console.log(str.startsWith('Hello'));  // true
console.log(str.startsWith('Hello', 0));  // true
console.log(str.startsWith('hello'));  // false
console.log(str.startsWith('world', 7));  // true

上述示例中,字符串 str 的开头是 'Hello',所以第一个和第二个 console.log() 语句返回 true。第三个语句中,'hello' 的大小写不匹配,所以返回 false。最后一个语句中,使用了可选的位置参数,指定从索引位置 7 开始搜索,由于字符串的第 7 个字符是 'w',所以返回 true

兼容性

startsWith() 方法在 ECMAScript 6 中被引入,因此在较旧的浏览器中可能不被支持。然而,可以使用 polyfill 或者使用其他方法来替代。

以下是一种在较旧的浏览器中模拟 startsWith() 方法的实现:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.substr(position, searchString.length) === searchString;
  };
}

在使用此 polyfill 之后,可确保在不支持 startsWith() 方法的浏览器中也能正常运行。

总结

startsWith() 方法是 JavaScript 字符串对象的一个实用方法,可用于检查一个字符串是否以指定的子字符串开头。它返回一个布尔值,可帮助我们快速判断字符串的起始内容。在使用前,需要注意兼容性问题,在需要支持较旧浏览器的情况下要考虑使用 polyfill 或替代方法。