
- 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
Reversing words within a string JavaScript
We are required to write a JavaScript function that takes in a string that might contain spaces. Our function should first split the string based on the spaces and then reverse and join and return the new string.
For example − If the input string is −
const str = 'this is a word';
Then the output should be −
const output = 'siht si a drow';
Example
const str = 'this is a word'; const reverseWords = (str = '') => { const strArr = str.split(' '); for(let i = 0; i < strArr.length; i++){ let el = strArr[i]; strArr[i] = el .split('') .reverse() .join(''); }; return strArr.join(' '); }; console.log(reverseWords(str));
Output
And the output in the console will be −
siht si a drow
- Related Articles
- Reversing words in a string in JavaScript
- Reversing words present in a string in JavaScript
- Reversing the words within keeping their order the same JavaScript
- Reversing the even length words of a string in JavaScript
- Reversing the order of words of a string in JavaScript
- Reversing the prime length words - JavaScript
- Reversing vowels in a string JavaScript
- Reversing alphabets in a string using JavaScript
- Reversing a string using for loop in JavaScript
- Reversing consonants only from a string in JavaScript
- Replace words of a string - JavaScript
- Sorting alphabets within a string in JavaScript
- Performing shifts within a string in JavaScript
- Reversing a string while maintaining the position of spaces in JavaScript
- Finding duplicate "words" in a string - JavaScript

Advertisements