跳到主要内容

JavaScript 程序:检查一个字符串是否以另一个字符串开头

要理解这个示例,你应该具备以下 JavaScript 编程 主题的知识:

示例 1:使用 startsWith()

// 程序检查字符串是否以另一个字符串开头

const string = "hello world";

const toCheckString = "he";

if (string.startsWith(toCheckString)) {
console.warn('字符串以 "he" 开头。');
} else {
console.warn(`字符串不以 "he" 开头。`);
}

输出

字符串以 "he" 开头。

在上述程序中,使用 startsWith() 方法来确定字符串是否以 'he' 开头。startsWith() 方法检查字符串是否以特定字符串开头。

使用 if...else 语句检查条件。

示例 2:使用 lastIndexOf()

// 程序检查字符串是否以另一个字符串开头

const string = "hello world";

const toCheckString = "he";

let result = string.lastIndexOf(toCheckString, 0) === 0;
if (result) {
console.warn('字符串以 "he" 开头。');
} else {
console.warn(`字符串不以 "he" 开头。`);
}

输出

字符串以 "he" 开头。

在上述程序中,使用 lastIndexOf() 方法检查字符串是否以另一个字符串开头。

lastIndexOf() 方法返回被搜索的字符串的索引(这里从第一个索引开始搜索)。

示例 3:使用正则表达式

// 程序检查字符串是否以另一个字符串开头

const string = "hello world";

const pattern = /^he/;

let result = pattern.test(string);

if (result) {
console.warn('字符串以 "he" 开头。');
} else {
console.warn(`字符串不以 "he" 开头。`);
}

输出

字符串以 "he" 开头。

在上述程序中,使用正则表达式模式和 test() 方法检查字符串。

/^ 表示字符串的开始。