
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Interchanging a string to a binary string in JavaScript
- Number difference after interchanging their first digits in JavaScript
- Swapping adjacent words of a String in JavaScript
- Program to find all words which share same first letters in Python
- Reversing words in a string in JavaScript
- Get distinct first words in a string with MongoDB?
- Get first three letters from every string in C#
- Replace words of a string - JavaScript
- Finding duplicate "words" in a string - JavaScript
- Finding the power of a string from a string with repeated letters in JavaScript
- Finding the number of words in a string JavaScript
- Reversing words present in a string in JavaScript
- Reversing the order of words of a string in JavaScript
- Reversing the even length words of a string in JavaScript
- Keeping only redundant words in a string in JavaScript

Advertisements