Advertisement
binibiningtinamoran

CustomSplit.js

May 27th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // WRITE A CUSTOM SPLIT() METHOD
  2.  
  3.  
  4. /*
  5.  Write a function that splits the receiving string parameter into an array of strings
  6.  by separating the string into substrings and return the array.
  7.  function (stringToSplit, separator)
  8.  
  9.  Example (‘a|b|c’, ‘|’ return [‘a’,’b’,’c’],
  10.  (bcAbd, ‘A’, return [‘bc’, ‘bd’],
  11.  (bacd, ‘X’ return [‘b’,’a’,’c’,’d’])
  12.  
  13.  (similar to built-in function split)
  14.  */
  15.  
  16. function customSplit(stringToSplit, separator) {
  17.     let output = [];
  18.     let currentIndex = 0;
  19.     let startIndex = 0;
  20.  
  21.     for (let i = 0; i < stringToSplit.length; i++) {
  22.         if (stringToSplit[i] === separator) {
  23.             output[currentIndex] = "";
  24.             for (let j = startIndex; j < i; j++) {
  25.                 output[currentIndex] += stringToSplit[j];
  26.             }
  27.             startIndex = i + 1;
  28.             currentIndex++;
  29.         }
  30.     }
  31.     output[currentIndex] = "";
  32.     for (let k = startIndex; k < stringToSplit.length; k++) {
  33.         output[currentIndex] += stringToSplit[k];
  34.     }
  35.  
  36.     return output;
  37. }
  38. // TESTS customSplit() function
  39. console.log("VNCE " + customSplit('bcAbd','')); // prints [ 'bc', 'bd' ]
  40. console.log(customSplit('a|b|c','|')); // prints [ 'a', 'b', 'c' ]
  41. console.log(customSplit('bacd','X')); // prints [ 'bacd' ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement