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