Finding letter distance in strings - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string as first argument and two single element strings. The function should return the distance between those single letter stings in the string taken as first argument.

For example −

If the three strings are −

const str = 'Disaster management';
const a = 'i', b = 't';

Then the output should be 4 because the distance between 'i' and 't' is 4

Example

Following is the code −

const str = 'Disaster management';
const a = 'i', b = 't';
const distanceBetween = (str, a, b) => {
   const aIndex = str.indexOf(a);
   const bIndex = str.indexOf(b);
   if(aIndex === -1 || b === -1){
      return false;
   };
   return Math.abs(aIndex - bIndex);
};
console.log(distanceBetween(str, a, b));

Output

Following is the output in the console −

4
raja
Published on 18-Sep-2020 09:41:32
Advertisements