Finding the immediate next character to a letter in string using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string of characters, str, and a single character, char.

Our function should construct a new string that contains the immediate next character present in str after each instance of char (if any).

Example

Following is the code −

 Live Demo

const str = 'this is a string';
const letter = 'i';
const findNextString = (str = '', letter = '') => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      const next = str[i + 1];
      if(letter === el && next){
         res += next;
      };
   };
   return res;
};
console.log(findNextString(str, letter));

Output

ssn
raja
Published on 19-Apr-2021 11:43:34
Advertisements