You can use the startsWith() method to determine whether a string starts with another string. This method is part of ES6 and can be used in the following ways:
let str = 'Hello World';
if (str.startsWith('Hello')) {
console.log('字符串以Hello开头');
} else {
console.log('字符串不以Hello开头');
}
This will output a string starting with Hello.
If the string you need to check is longer, you can store it in a variable like this:
let str1 = 'Hello World';
let str2 = 'Hello';
if (str1.startsWith(str2)) {
console.log('字符串以Hello开头');
} else {
console.log('字符串不以Hello开头');
}
This will output "String starts with Hello" to the console.
Please like it if it is useful, and develop a good habit!
Please leave a message for questions, exchanges, and encouragement!