Advertisement
dimipan80

Text Modifier

Nov 17th, 2014
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a JavaScript function fixCasing(str) that accepts a text as a parameter. The function must change
  2. the text in all regions as follows: <upcase>text</upcase> to uppercase; <lowcase>text</lowcase> to lowercase;
  3. <mixcase>text</mixcase> to mixed casing (randomly).
  4. Write JS program caseFixer.js that invokes your function with the sample input data below and prints
  5. the output at the console. */
  6.  
  7. "use strict";
  8.  
  9. function fixCasing(str) {
  10.     var upperCaseRegex = /<upcase>(\w+\W*\w+)<\/upcase>/g;
  11.     var match = upperCaseRegex.exec(str);
  12.     while (match != null) {
  13.         str = str.replace(match[0], match[1].toUpperCase());
  14.         match = upperCaseRegex.exec(str);
  15.     }
  16.  
  17.     var lowerCaseRegex = /<lowcase>(\w+\W*\w+)<\/lowcase>/g;
  18.     match = lowerCaseRegex.exec(str);
  19.     while (match != null) {
  20.         str = str.replace(match[0], match[1].toLowerCase());
  21.         match = lowerCaseRegex.exec(str);
  22.     }
  23.  
  24.     function toMixCase(word) {
  25.         var charsArr = word.split('').filter(Boolean);
  26.         for (var i = 0; i < charsArr.length; i += 1) {
  27.             var letter = charsArr[i];
  28.             if (Math.round(Math.random())) {
  29.                 charsArr[i] = letter.toUpperCase();
  30.             } else {
  31.                 charsArr[i] = letter.toLowerCase();
  32.             }
  33.         }
  34.  
  35.         return charsArr.join('');
  36.     }
  37.  
  38.     var mixCaseRegex = /<mixcase>(\w+\W*\w+)<\/mixcase>/g;
  39.     match = mixCaseRegex.exec(str);
  40.     while (match != null) {
  41.         str = str.replace(match[0], toMixCase(match[1]));
  42.         match = mixCaseRegex.exec(str);
  43.     }
  44.  
  45.     return str;
  46. }
  47.  
  48. console.log(fixCasing(
  49.     "We are <mixcase>living</mixcase> in a <upcase>yellow submarine</upcase>." +
  50.     "We <mixcase>don't</mixcase> have <lowcase>anything</lowcase> else."));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement