Algorithm


  1. Input: Accept two strings as input - the main string and the substring to check for at the beginning.
  2. Initialize: Set two pointers, one for each string (main string and substring). Let's call them mainPointer and subPointer.
  3. Loop: Iterate through each character of the substring.
    • If the character at the subPointer position in the substring is equal to the character at the mainPointer 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.
  4. Check: After the loop completes, if all characters in the substring match the corresponding characters in the main string, return true.
  5. 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

x
+
cmd
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

x
+
cmd
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

x
+
cmd
The string starts with "he".
Advertisements

Demonstration


JavaScript Program to Check if a String Starts With Another String-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way