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
Selected Reading
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 −
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
Advertisements
