Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'
like image 377
hackermann Avatar asked Oct 16 '25 14:10

hackermann


1 Answers

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.

like image 159
Tᴀʀᴇǫ Mᴀʜᴍᴏᴏᴅ Avatar answered Oct 18 '25 07:10

Tᴀʀᴇǫ Mᴀʜᴍᴏᴏᴅ