settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Check if String starts with a given Substring in JavaScript

+3 votes

Write a JavaScript function that checks if a given string, starts with a given substring.

The input comes as 2 string arguments:

  • The first string will represent the main one.
  • The second one will represent the substring.

Examples:

Input:
How have you been?
how

Output:
false


Input:
The quick brown fox…
The quick brown fox…

Output:
true


Input:
Marketing Fundamentals, starting 19/10/2016
Marketing Fundamentals, sta

Output:
true


The output is either “true” or “false” based on the result of the check.

The comparison is case-sensitive!

asked in JavaScript category by user icabe

2 Answers

+2 votes

My js code:

function checkStart(input, check) {
    let checkSub = input.substr(0, check.length);
    if (checkSub == check) {
        console.log(true);
    } else {
        console.log(false);
    }

}

//checkStart("How have you been?", "how");
checkStart("Marketing Fundamentals, starting 19/10/2016","Marketing Fundamentals, sta");

 

answered by user Jolie Ann
0 votes

..and mine:

(text,substr)=>text.startsWith(substr);

 

answered by user nikole
...