Write a function to reverse words in a string

I got below test as a part of my job interview and I know how to reverse a string but don’t know how to reverse every third word in a string.

Test is

Using ES5 or ES6, write a function ‘reverseStringWords’ that will reverse every **third** word in a string. The string will only contain a single space between words and there will be no punctuation.

for example
string (london glasgow manchester edinburgh oxford liverpool)
should become
string (manchester lonodn glasgow liverpool edinburgh oxford)

Your help would be much appriciated.

Many thanks

  1. You know how to reverse a string, put that knowledge in a function.
  2. Loop over the words in the string - you know The string will only contain a single space between words, so you can easily split it into words.
  3. Put the words back into another string, with the caveat that every third word, you need to run the function from 1.

Also, the example doesn’t quite make sense, it hasn’t reversed every third word, it’s reversed the first word and [seemingly randomly] shifted the order around.

Hi @DanCouper , I am also confused about this test as they only provided me below sentence

Using ES5 or ES6, write a function ‘reverseStringWords’ that will reverse every **third** word in a string. The string will only contain a single space between words and there will be no punctuation.

I am not sure either they are asking to reverse every third word in its own position in string such as “xyz abc mno” should become " xyz abc onm" or they are asking to reverse whole sentence.

Many thanks

Yea, “every third word” implies that you’re just reversing every third word in position, the example given seems to have no pattern to it, it looks completely random unless I’m missing something :confounded:

I will update you soon.

Thank you.

Hi @DanCouper, I came up with this code

function reverseStringWords (sentence) {
  return sentence.split(' ').map(function(word) {
    return word.split('').reverse().join('');
  }).join(' ');
}

console.log(reverseStringWords("london glasgow manchester edinburgh oxford liverpool"));

This is reversing every word , please let me know how to reverse only third word.

Many thanks

function reverseStringWords (sentence) {
  return sentence.split(' ').map(function(word, index) {
    if ((index+1)%3==0) return word.split('').reverse().join('');
    else return word;
  }).join(' ');
}

console.log(reverseStringWords("london glasgow manchester edinburgh oxford liverpool"));

Adding a second parameter to the map function gives you access to the index.

Index plus 1, modulus 3, refers only to every 3rd index. (the index starts at zero).