JS里 字符串的startsWith()方法

191 阅读1分钟

前言

JS的String.startsWith()方法


JS的String.startsWith()方法

startsWith() 是 JavaScript 字符串对象的一个方法,用于判断一个字符串是否以指定的子字符串开头。下面从基本语法、参数、返回值、使用示例、兼容性等方面详细介绍:

1. 基本语法

str.startsWith(searchString[, position])

参数
searchString:必需,要搜索的子字符串。它指定了用来检查是否作为原字符串起始部分的内容。
position:可选,是一个整数,用于指定开始搜索的位置,默认值为 0,即从字符串的开头开始搜索。

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

2. 示例

示例 1:基本使用
const str = "Hello, World!";
console.log(str.startsWith("Hello"));  // 输出: true

示例 2:指定搜索位置
const str = "Hello, World!";
console.log(str.startsWith("World", 7));  // 输出: true

示例 3:使用 startsWith() 统计数组中是某字符串前缀的元素数量
function countPrefixes(words, s) {
    let count = 0;
    for (const word of words) {
        if (s.startsWith(word)) {
            count++;
        }
    }
    return count;
}

const words = ["a", "ab", "abc"];
const s = "abcde";
console.log(countPrefixes(words, s));  // 输出: 3

3. 注意事项

兼容性 startsWith() 方法在现代浏览器中得到了广泛支持,但在旧版本的 Internet Explorer 中不支持。如果需要在旧浏览器中使用该方法,可以使用以下的兼容代码:

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(search, pos) {
        return this.substr(!pos || pos < 0? 0 : +pos, search.length) === search;
    };
}

注意事项 startsWith() 方法是区分大小写的,例如 "Hello".startsWith("hello") 会返回 false。 searchString 参数必须是字符串类型,如果传入的不是字符串,会先将其转换为字符串再进行比较。