Reversing words present in a string in JavaScript


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

Updated on: 17-Apr-2021

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements