Reversing words present in a string in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string that represents a sentence.

Our function should reverse the order of words present in the string and return the new string.

It means that the last word should become the first, second last should be the second and so on.

Example

Following is the code −

 Live Demo

const str = 'this is some random string text';
const reverseWords = (str = '') => {
   const strArr = str.split(' ');
   strArr.reverse();
   const reversedStr = strArr.join(' ');
   return reversedStr;
};
console.log(reverseWords(str));

Output

Following is the console output −

text string random some is this
raja
Published on 17-Apr-2021 11:16:30
Advertisements