JavaScript: How would I reverse ONLY the words in a string

- 1 answer

Ad

How would i write a function that takes one argument that is a sentence and returns a new sentence where all words are reversed but kept in the same order as the original sentence?

Test Case:

wordsReverser("This is fun, hopefully.");

Would return:

"sihT si nuf, yllufepoh."

This is what I have so far but notice that I cant get the period and comma to stay in place. I don't know if this was a typo by the interviewer or what?

function wordsReverser(str){
  return str.split(' ').
    map(function(item) {    
        return item.split('').reverse().join('');
    }).join(' ');
}

wordsReverser("This is fun, hopefully.");
//Output: 'sihT si ,nuf .yllufepoh'
Ad

Answer

Ad

Try this way:

function wordsReverser(str){
  return str.replace(/[a-zA-Z]+/gm, function(item) {    
        return item.split('').reverse().join('');
    });
}

wordsReverser("This is fun, hopefully.");
//Output: 'sihT si nuf, yllufepoh.'

How It Works: the replace() function will find each word and pass to the function which will reverse the word (the function returns the reverse word which replaces the word in the string) and all other should remain as that was before.

Ad
source: stackoverflow.com
Ad