I write a function that inverts all the words, but the order of the words remains the same:

reverseWords ("This is an example!"); // returns "sihT si na! elpmaxe"

my code is:

function reverseWords(str) { // Go for it return str.split("").reverse().join(""); } reverseWords("This is an example!"); 

I get this: "! elpmaxe na si sihT" and you need to keep order, how?

  • one
    split into array. We iterate over the array and for each element do reverse . Then we glue the array back through the gap. Everything. - Chubatiy

3 answers 3

 function reverseWords(str) { return str.split(" ").map( function(a) {return a.split("").reverse().join("")} ).join(" "); } 

At first we break into words, then for each word we break into letters and unfold, then we combine all this again

  • I can't add your code to my function - spectre_it
  • @ stas0k How not to succeed return str.мой_код - Mike

Try this:

 function reverseWords(str) { str = str.split(" "); var res = []; for (var i = 0; i < str.length; i++){ res.push (str[i].split("").reverse().join("")); } return res.join(" "); } console.log(reverseWords("This is an example!")); 

     // es6 const reverseWords = (str) => str .split(' ') .map( word => word.split('').reverse().join('') ) .join(' '); reverseWords('This is an example!');