JavaScript: How would I reverse ONLY the words in a string
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
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad