
- 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 only the odd length words - 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.
Let’s say the following is our string −
const str = 'hello beautiful people';
The odd length words are −
hello beautiful
Example
Let us write the code for this function.
const str = 'hello beautiful people'; 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 in the console −
olleh lufituaeb people
- Related Articles
- Reverse the words in the string that have an odd number of characters in JavaScript
- Reverse all the words of sentence JavaScript
- Reversing the prime length words - JavaScript
- All possible odd length subarrays JavaScript
- Adding only odd or even numbers JavaScript
- Returning only odd number from array in JavaScript
- Reversing the even length words of a string in JavaScript
- Maximum length product of unique words in JavaScript
- Keeping only redundant words in a string in JavaScript
- Sum of All Possible Odd Length Subarrays in JavaScript
- Finding the only even or the only odd number in a string of space separated numbers in JavaScript
- How to reverse a string using only one variable in JavaScript
- Arranging words by their length in a sentence in JavaScript
- Reverse Only Letters in Python
- Reverse Words in a String in C++

Advertisements