示例 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()
方法检查字符串。
/^
表示字符串的开始。