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

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 1:使用 startsWith()

// program to check if a string starts with another string

const string = 'hello world';

const toCheckString = 'he';

if(string.startsWith(toCheckString)) {
    console.warn('The string starts with "he".');
}
else {
    console.warn(`The string does not starts with "he".`);
}

输出

The string starts with "he".

在上面的程序中,startsWith() 方法用于确定字符串是否以 “he” 开头。startsWith() 方法检查字符串是否以特定字符串开头。

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


示例 2:使用 lastIndexOf()

// program to check if a string starts with another string

const string = 'hello world';

const toCheckString = 'he';

let result = string.lastIndexOf(toCheckString, 0) === 0;
if(result) {
    console.warn('The string starts with "he".');
}
else {
    console.warn(`The string does not starts with "he".`);
}

输出

The string starts with "he".

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

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


示例 3:使用 RegEx

// program to check if a string starts with another string

const string = 'hello world';

const pattern = /^he/;

let result = pattern.test(string);

if(result) {
    console.warn('The string starts with "he".');
}
else {
    console.warn(`The string does not starts with "he".`);
}

输出

The string starts with "he".

在上面的程序中,使用 RegEx 模式和 test() 方法检查字符串。

/^ 表示字符串的开头。


另请阅读

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

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

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

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