Advertisement
dimipan80

Reverse Every Word in a String

Nov 15th, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a JavaScript function reverseWordsInString(str) that accepts as a parameter a string and reverses
  2. the characters of every word in the string but leaves the words in the same order. Words are considered
  3. to be sequences of characters separated by spaces. Write a JavaScript program reverseWords.js that prints
  4. on the console the output. */
  5.  
  6. "use strict";
  7.  
  8. function reverseWordsInString(str) {
  9.     var text = str.split(/\s+/g).filter(Boolean);
  10.     for (var i = 0; i < text.length; i += 1) {
  11.         var reversedStr = '';
  12.         for (var j = text[i].length - 1; j >= 0; j -= 1) {
  13.             reversedStr = reversedStr.concat(text[i].charAt(j))
  14.         }
  15.         text[i] = reversedStr;
  16.     }
  17.  
  18.     return text.join(' ');
  19. }
  20.  
  21. console.log(reverseWordsInString('Hello, how are you.'));
  22. console.log(reverseWordsInString('Life is pretty good, isn’t it?'));
  23. console.log(reverseWordsInString('JavaScript is a dynamic computer programming language.'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement