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