Start a personal dev blog on your domain for free with Hashnode and grow your readership.
Get Started

Easy peasy reverse words

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(' ');
}
Start a personal dev blog on your domain for free and grow your readership.

3.4K+ developers have started their personal blogs on Hashnode in the last one month.

Write in Markdown · Publish articles on custom domain · Gain readership on day zero · Automatic GitHub backup and more

Comments (2)

Apoorv Tyagi's photo

Nice Post Divyajyoti Ukirde.

I like these one liners clever tricks😎.