Return string with n
or more lettered words reversed, given that string consists of letters and spaces only. (i.e. n is the word length)
A single line clever solution would be by using regex
.
If n
is predetermined, like n = 5
,
const revWords = (str) => {
return str.replace(/\w{5,}/g, function(w) {
return w.split('').reverse().join(''); });
}
But not all clever solutions are good to go on production. It does fit this problem but difficult to mutate or reuse the technique if problem changes. The next one's better.
const revWords = (str, n) => {
return str.split(' ').map(function (word) {
return (word.length >= n) ?
word.split('').reverse().join('') : word;
}).join(' ');
}
Top comments (5)
If I understood the problem correctly, why don't you just do this:
Julian, I believe Divyajyoti is missing a key part of the description (from my understanding). She wants to reverse the words in a string, not the whole string.
This is what your example produces:
This is what her solution produces:
That being said, I feel the original solution could be improved. It could be simplified a lot. There is no need to know word length.
If the question has word length specifically mentioned then you need to apply my solution. I have made the text bold, to avoid confusion. The
n
there is word-length basically and only those words need to be reversed that satisfy the word-length condition.Ah, you only want n length or above words in a string reversed in place. Now it makes more sense. Danke!
Oh, yeah I totally missed that because I was on mobile. Thanks for clearing it up, your solution is probably the shortest you can do! π