Advertisement
svetlai

Change Case

May 27th, 2015
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function changeCase(text) {
  2.     var currentSymbol,
  3.         openTag = '<',
  4.         closeTag = '>',
  5.         isTag = false,
  6.         currentTag = '',
  7.         result = '',
  8.         tags = [];
  9.  
  10.     for (var i = 0, l = text.length; i < l; i += 1) {
  11.         currentSymbol = text[i];
  12.  
  13.         if (currentSymbol === openTag) {
  14.             isTag = true;
  15.             continue;
  16.         }
  17.  
  18.         if (currentSymbol === closeTag) {
  19.             isTag = false;
  20.             continue;
  21.         }
  22.  
  23.         if (isTag) {
  24.             switch (currentSymbol) {
  25.                 case 'u':
  26.                     currentTag = '<upcase>';
  27.                     tags.push(currentTag);
  28.                     i += currentTag.length - 2;
  29.                     break;
  30.                 case 'm':
  31.                     currentTag = '<mixcase>';
  32.                     tags.push(currentTag);
  33.                     i += currentTag.length - 2;
  34.                     break;
  35.                 case 'l':
  36.                     currentTag = '<lowcase>';
  37.                     tags.push(currentTag);
  38.                     i += currentTag.length - 2;
  39.                     break;
  40.                 case '/':
  41.                     tags.pop();
  42.                     i += currentTag.length - 2;
  43.                     if (tags.length > 0) {
  44.                         currentTag = tags[tags.length - 1];
  45.                     } else {
  46.                         currentTag = '';
  47.                     }
  48.                     break;
  49.             }
  50.  
  51.             isTag = false;
  52.             continue;
  53.         }
  54.  
  55.         switch (currentTag) {
  56.             case '<upcase>':
  57.                 result += currentSymbol.toUpperCase();
  58.                 break;
  59.             case '<mixcase>':
  60.                 result += Math.random() < 0.5 ? currentSymbol.toUpperCase() : currentSymbol.toLowerCase();
  61.                 break;
  62.             case '<lowcase>':
  63.                 result += currentSymbol.toLowerCase();
  64.                 break;
  65.             default:
  66.                 result += currentSymbol;
  67.                 break;
  68.         }
  69.     }
  70.  
  71.     return result;
  72. }
  73.  
  74. var text = 'We are <upcase><mixcase><lowcase></lowcase>living</mixcase> in </upcase> a <upcase>yellow submarine</upcase>. We <mixcase>don\'t</mixcase> have <lowcase>anything</lowcase> else.';
  75.  
  76. console.log(changeCase(text));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement