pertrai1 pertrai1 - 4 months ago 18
Javascript Question

reverse string greater than certain length

I am working on a problem where I need to be able to reverse a sentence but only words that are greater than 4 can be reversed. the rest of the words must be the same as they are. I have tried to check to see if length is greater than 4 but that does not return the result I am looking for. All I need is to reverse any words that are greater than 4 in the sentence. Any help is greatly appreciated.

Edit: Here is the simple of what I know how to do. It reverses all of the sentence. I am sure that there needs to be some way to break apart each word and determine the length of the word and then bring the sentence back together, but I don't know how that would be done.

var sentence = "This could be the answer I need";

if (sentence.length > 4) {
console.log( sentence.split('').reverse().join(''));
}


Thank you

Answer

In Short:

var s = 'This is a short sentence'
  , e = s.split(' ').map(function(v){ return v.length>4?v.split('').reverse().join(''):v; }).join(' ');

console.log(e); // 'This is a trohs ecnetnes'

Explained:

var s = 'This is a short sentence' // set test sentence
  , e = s.split(' ')               // 'This is a short sentence' ==> ['This','is','a','short','sentence']
         .map(function(v,i,a){     // REPLACE the value of the current index in the array (run for each element in the array)
            return v.length > 4    // IF the length of the a 'word' in the array is greater than 4
                 ? v.split('')     // THEN return: 'word' ==> ['w','o','r','d']
                    .reverse()     // ['w','o','r','d'] ==> ['d','r','o','w']
                    .join('')      // ['d','r','o','w'] ==> 'drow'
                 : v;              // OR return: the original 'word'
         }).join(' ');             // ['This','is','a','trohs','ecnetnes'] ==> 'This is a trohs ecnetnes'

console.log(e); // 'This is a trohs ecnetnes'
Comments