Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
-
Split the string:
split(' ')divides the input into an array of two words - Extract first characters: Get the first character from each word using bracket notation
-
Build new words: Use
substring(1)to get all characters except the first, then prepend the swapped character - 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.
Advertisements
