For people looking into this problem now, think whether your application doesn't need to deal with punctuation marks (e.g. not moving punctuation marks around) or flipped hyphenated words (e.g. check-in should be ni-kcehc or kcehc-ni ?).
For example:
- "ignorance is bliss?!" should really be "ecnarongi si !?ssilb" ?
- "Merry-go-round" should be "dnuor-og-yrreM" or "yrreM-og-dnuor" ?
The following solution doesn't move punctuation marks and it doesn't flip hyphenated words:
/**
* 1. Split "non letters"
* 2. Reverse each piece
* 3. Join the pieces again, replacing them by " "
* 4. Split all characters
* 5. Replace " " by the original text char
*/
function reverseWords(text) {
return text.split(/[^A-Za-zÀ-ÿ]/g)
.map(w => w.split("").reverse().join(""))
.join(" ")
.split("")
.map((char, i) => char === " " ? text[i] : char)
.join("")
}
return
inside a multi-iteration for-loop ?! – Dizzys = 'abd fhe kdj'; reverseInPlace(s); console.log(s)
. – Heikeheil"abd fhe kdj".split( " " ).map( s => s.split("").reverse().join( "" ) ).join( " " )
– Kaiulani