Algorithm
- Input: Accept two strings as input - the main string and the substring to check for at the beginning.
- Initialize: Set two pointers, one for each string (main string and substring). Let's call them
mainPointer
andsubPointer
. - Loop: Iterate through each character of the substring.
- If the character at the
subPointer
position in the substring is equal to the character at themainPointer
position in the main string, continue to the next character in both strings. - If any character doesn't match, return false as the main string doesn't start with the given substring.
- If the character at the
- Check: After the loop completes, if all characters in the substring match the corresponding characters in the main string, return true.
- End: If the loop completes and no mismatch is found, the main string starts with the given substring.
Code Examples
#1 Code Example- Using startsWith()
Code -
Javascript Programming
// 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".`);
}
Copy The Code &
Try With Live Editor
Output
The string starts with "he".
#2 Code Example- Using lastIndexOf()
Code -
Javascript Programming
// 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".`);
}
Copy The Code &
Try With Live Editor
Output
The string starts with "he".
#3 Code Example- Using RegEx
Code -
Javascript Programming
// 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".`);
}
Copy The Code &
Try With Live Editor
Output
The string starts with "he".
Demonstration
JavaScript Program to Check if a String Starts With Another String-DevsEnv