Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

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

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

在本例中,您将学习编写一个 JavaScript 程序,该程序将检查一个字符串是否以另一个字符串开头。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 字符串 Javascript String startsWith() JavaScript 字符串 lastIndexOf() 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: 使用正则表达式

// 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()方法检查字符串。
/^ 表示字符串的开始。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4