Return TRUE if the first string starts with a specific second string JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a JavaScript function that takes in two strings and checks whether first string starts with second or not

For example −

If the two strings are:
“Disaster management report”
“Disas”
Then our function should return true

Let's write the code for this function −

Example

const first = 'The game is on';
const second = 'The';
const startsWith = (first, second) => {
   const { length } = second;
   const { length: l } = first;
   const sub = first.substr(0, length);
   return sub === second;
};
console.log(startsWith(first, second));

Output

The output in the console will be −

true
raja
Published on 31-Aug-2020 15:50:45
Advertisements