
- 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
Reverse the words in the string that have an odd number of characters in JavaScript
We are required to write a JavaScript function that takes in a string and reverses the words in the string that have an odd number of characters in them.
Any substring in the string qualifies to be a word, if either it is encapsulated by two spaces on either ends or present at the end or beginning and followed or preceded by a space.
Example
The code for this will be −
const str = 'hello world, how are you'; const idOdd = str => str.length % 2 === 1; const reverseOddWords = (str = '') => { const strArr = str.split(' '); return strArr.reduce((acc, val) => { if(idOdd(val)){ acc.push(val.split('').reverse().join('')); return acc; }; acc.push(val); return acc; }, []).join(' '); }; console.log(reverseOddWords(str));
Output
Following is the output on console −
olleh world, woh era uoy
- Related Articles
- Reverse only the odd length words - JavaScript
- Finding the number of words in a string JavaScript
- Python Program to Calculate the Number of Words and the Number of Characters Present in a String
- Reverse all the words of sentence JavaScript
- Counting the number of redundant characters in a string - JavaScript
- Reverse Words in a String in C++
- Take an array and find the one element that appears an odd number of times in JavaScript
- Replace all characters in a string except the ones that exist in an array JavaScript
- Reverse words in a given String in Java
- Reverse words in a given String in Python
- Reverse Words in a String II in C++
- Reverse words in a given String in C#
- Number of non-unique characters in a string in JavaScript
- How to find the one integer that appears an odd number of times in a JavaScript array?
- C# program to Reverse words in a string

Advertisements