Interchanging first letters of words in a string in JavaScript

We need to write a JavaScript function that takes a string containing exactly two words and swaps their first letters to create a new string.

Problem Statement

Given a string with two words separated by a space, we want to interchange the first character of each word while keeping the rest of the characters in their original positions.

Example

For input "hello world", we should get "wello horld" where 'h' and 'w' are swapped.

const str = 'hello world';
const interchangeChars = (str = '') => {
    const [first, second] = str.split(' ');
    const fChar = first[0];
    const sChar = second[0];
    const newFirst = sChar + first.substring(1, first.length);
    const newSecond = fChar + second.substring(1, second.length);
    const newStr = newFirst + ' ' + newSecond;
    return newStr;
};
console.log(interchangeChars(str));

Output

wello horld

How It Works

The function follows these steps:

  1. Split the string: split(' ') divides the input into an array of two words
  2. Extract first characters: Get the first character from each word using bracket notation
  3. Build new words: Use substring(1) to get all characters except the first, then prepend the swapped character
  4. Combine results: Join the modified words with a space

Alternative Approach

Here's a more concise version using template literals:

const interchangeCharsShort = (str) => {
    const [first, second] = str.split(' ');
    return `${second[0]}${first.slice(1)} ${first[0]}${second.slice(1)}`;
};

console.log(interchangeCharsShort('apple banana'));
console.log(interchangeCharsShort('quick brown'));
bpple aanana
brown quick

Conclusion

This solution efficiently swaps the first letters of two words by splitting the string, extracting characters, and reconstructing the result. The approach works reliably for any two-word input string.

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

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements