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

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).

Problem

Given a string and a target letter, we need to find all characters that immediately follow each occurrence of the target letter and combine them into a new string.

Solution

We'll iterate through the string and check each character. When we find a match with our target letter, we'll add the next character to our result string.

const str = 'this is a string';
const letter = 'i';

const findNextString = (str = '', letter = '') => {
    let res = '';
    for(let i = 0; i 

ssn

How It Works

The function examines each character in the string:

  • At position 1: 'i' matches, next character is 's' ? add 's'
  • At position 5: 'i' matches, next character is 's' ? add 's'
  • At position 12: 'i' matches, next character is 'n' ? add 'n'

Example with Different Input

const text = 'hello world';
const targetChar = 'l';

console.log(findNextString(text, targetChar));
lo

Edge Cases

The function handles edge cases automatically:

// Target letter at end of string
console.log(findNextString('test', 't')); // 'e' (only first match)

// Target letter not found
console.log(findNextString('hello', 'z')); // '' (empty string)

// Empty string
console.log(findNextString('', 'a')); // '' (empty string)
e

Conclusion

This approach efficiently finds characters that follow a target letter by iterating through the string once. The function safely handles edge cases like end-of-string positions and missing target letters.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements