Implementing custom function like String.prototype.split() function in JavaScript



Problem

We are required to write a JavaScript function that lives on the prototype object of the String class.

It should take in a string separator as the only argument (although the original split function takes two arguments). And our function should return an array of parts of the string separated and split by the separator.

Example

Following is the code −

 Live Demo

const str = 'this is some string';
String.prototype.customSplit = (sep = '') => {
   const res = [];
   let temp = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(el === sep || sep === '' && temp){
         res.push(temp);
         temp = '';
      };
      if(el !== sep){
         temp += el;
      }
   };
   if(temp){
      res.push(temp);
      temp = '';
   };
   return res;
};
console.log(str.customSplit(' '));

Output

[ 'this', 'is', 'some', 'string' ]

Advertisements