Swap the words of a string in Javascript

Viewed 1102

I want to swap words of string in such a way that the first word is swapped with the last word ,the second word with the second last word and so on using plain javascript. Eg :- "Secret Life is Beautiful Key" Output :- "Key Beautiful is Life Secret"

2 Answers

Hey the easiest solution would be:

  const str = 'Secret Life is Beautiful Key'

  console.log(str.split(' ').reverse().join(' '))

I hope this helps

var str = 'Secret Life is Beautiful Key';
var reversed = str.split(' ').reverse().join(' ');
console.log(reversed);

Related