[JS Practice] Reverse words(反转字符)

Title :

Reverse words(反转字符)


Write a reverseWords function that accepts a string a parameter, and reverses each word in the string.


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

My solution :

function reverseWords(str) {
 var strArr = str.split(" "); // Split string by whitespace <a>通过空白字符切割原来的字符</a>
 var retArr = []; // Init array <a>初始化一个空数组</a>
 strArr.forEach(function(element) {
   var word = element.split("").reverse().join(""); // str to arr and then reverse  <a>把字符转化成数组 然后</a><a>反转</a>
 return retArr.join(" ");


Ref. from codewars


One comment on “[JS Practice] Reverse words(反转字符)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s