- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding letter distance in strings - JavaScript
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
- Related Articles
- Missing letter from strings in JavaScript
- Finding missing letter in a string - JavaScript
- Finding word starting with specific letter in JavaScript
- Finding gcd of two strings in JavaScript
- Finding hamming distance in a string in JavaScript
- Finding shared element between two strings - JavaScript
- Hamming Distance between two strings in JavaScript
- Finding distance to next greater element in JavaScript
- Finding the immediate next character to a letter in string using JavaScript
- Finding the intersection of arrays of strings - JavaScript
- Finding all the longest strings from an array in JavaScript
- Finding and returning uncommon characters between two strings in JavaScript
- Finding how many times a specific letter is appearing in a sentence in JavaScript
- Finding the longest common consecutive substring between two strings in JavaScript
- Finding distance between two points in a 2-D plane using JavaScript

Advertisements