Return a splitted array of the string based on all the specified separators - JavaScript


We are required to write a JavaScript function that takes in a string and any number of characters specified as separators. Our function should return a splitted array of the string based on all the separators specified.

For example −

If the string is −

const str = 'rttt.trt/trfd/trtr,tr';

And the separators are −

const sep = ['/', '.', ','];

Then the output should be −

const output = [ 'rttt', 'trt', 'trfd', 'trtr' ];

Example

Following is the code −

const str = 'rttt.trt/trfd/trtr,tr';
const splitMultiple = (str, ...separator) => {
   const res = [];
   let start = 0;
   for(let i = 0; i < str.length; i++){
      if(!separator.includes(str[i])){
         continue;
      };
      res.push(str.substring(start, i));
      start = i+1;
   };
   return res;
}; 
console.log(splitMultiple(str, '/', '.', ','))

Output

This will produce the following output on console −

[ 'rttt', 'trt', 'trfd', 'trtr' ]

Updated on: 09-Nov-2020

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements