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


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

Updated on: 31-Aug-2020

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements