Interchanging first letters of words in a string in JavaScript


Problem

We are required to write a JavaScript function that takes in a string that contains exactly two words.

Our function should construct and return a new string in which the first letter of the words are interchanged with each other.

Example

Following is the code −

 Live Demo

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

Following is the console output −

wello horld

Updated on: 19-Apr-2021

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements