Advertisement
binibiningtinamoran

CustomTrim.js

May 27th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // WRITE A CUSTOM TRIM METHOD
  2.  
  3.  
  4. // Write a naive version of the trim() method.
  5.  
  6. function omitAllWhitespaces(word) {
  7.     let newWord = "";
  8.  
  9.     for (let letter of word) {
  10.         if (letter !== " " && letter !== "\n" && letter !== "\t") {
  11.             newWord += letter;
  12.         }
  13.     }
  14.     return newWord;
  15. }
  16.  
  17. // Removes all manner of whitespaces on the right of the string
  18. let omitRightWhitespaces = (word) => {
  19.     let newWord = "";
  20.  
  21.     let i = word.length-1;
  22.     while (i >= 0 && word[i] === " " || word[i] === "\t" || word[i] === "\n") {
  23.         i--;
  24.     }
  25.     // Manual "substring" implementation below
  26.     let limit = 0;
  27.     for (let m = 0, length = word.length; m <= i && limit < length; m++) {
  28.         newWord += word[m];
  29.         limit++;
  30.     }
  31.     return newWord;
  32. }
  33.  
  34. // Removes all manner of whitespaces on the left of the string
  35. let omitLeftWhitespaces = (word) => {
  36.     let newWord = "";
  37.     let j = 0;
  38.     while (j < word.length && word[j] === " " || word[j] === "\t" || word[j] === "\n") {
  39.         j++;
  40.     }
  41.     // Manual "substring" implementation below
  42.     let limit = j;
  43.     for (let m = j, length = word.length; m >= j && limit < length; m++) {
  44.         newWord += word[m];
  45.         limit++;
  46.     }
  47.     return newWord;
  48. }
  49.  
  50. // Removes all manner of whitespaces on the left and right of the string, not in between!
  51. let omitRightAndLeftWhitespaces = (word) => {
  52.  
  53.     let newWord ="";
  54.  
  55.     // Delete whitespace on right!
  56.     let i = word.length-1;
  57.     while (i >= 0 && word[i] === " " || word[i] === "\t" || word[i] === "\n") {
  58.         i--;
  59.     }
  60.  
  61.     // Delete whitespaces on left
  62.     let j = 0;
  63.     while (j < word.length && word[j] === " " || word[j] === "\t" || word[j] === "\n") {
  64.         j++;
  65.     }
  66.  
  67.     // Manual implementation of 'substring' using the j and i indices obtained from the while loops above.
  68.     let limit = j;
  69.     for (let k = j, length = word.length; k <= i && limit < length; k++) {
  70.         newWord += word[k];
  71.         limit++;
  72.     }
  73.     return newWord;
  74. }
  75.  
  76. console.log(omitRightAndLeftWhitespaces('\t\t   javascript is fun!\t\t'));
  77. // Output is: javascript is fun!
  78.  
  79. console.log(omitLeftWhitespaces('       \t\t\t\t\t\t\t\t\   angelo '));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement