
- 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 a string while maintaining the position of spaces in JavaScript
Problem
We are required to write a JavaScript function that takes in a string that might contain some spaces.
Our function should reverse the words present in the string internally without interchange the characters of two separate words or the spaces.
Example
Following is the code −
const str = 'this is normal string'; const reverseWordsWithin = (str = '') => { let res = ""; for (let i = str.length - 1; i >= 0; i--){ if(str[i] != " "){ res += str[i]; }; if(str[res.length] == " "){ res += str[res.length]; }; }; return res; }; console.log(reverseWordsWithin(str));
Output
gnir ts lamron sisiht
- Related Articles
- Reversing and preserving spaces in JavaScript
- Reversing vowels in a string JavaScript
- Reversing the order of words of a string in JavaScript
- Reversing words in a string in JavaScript
- Reversing the even length words of a string in JavaScript
- Reversing array without changing the position of certain elements JavaScript
- Reversing alphabets in a string using JavaScript
- Reversing words within a string JavaScript
- Reversing words present in a string in JavaScript
- Finding number of spaces in a string JavaScript
- Reversing a string using for loop in JavaScript
- Reversing consonants only from a string in JavaScript
- Find number of spaces in a string using JavaScript
- Remove extra spaces in string JavaScript?
- Removing all spaces from a string using JavaScript

Advertisements