Syntax error Is it possible to have JavaScript split() start at index 1?

Is it possible to have JavaScript split() start at index 1?



As of the official String.prototype.split() method there exist no way to start splitting a string from index 1 or for general from any index n, but with a little tweak in the way we use split(), we can achieve this functionality.

We followed the following approach −

We will create two arrays −

  • One that is splitted from 0 to end --- ACTUAL
  • Second that is splitted from 0 TO STARTPOSITION --- LEFTOVER

Now, we iterate over each element of leftover and splice it from the actual array. Thus, the actual array hypothetically gets splitted from STARTINDEX to END.

Example

const string = 'The quick brown fox jumped over the wall';
const returnSplittedArray = (str, startPosition, seperator=" ") => {
   const leftOver = str.split(seperator, startPosition);
   const actual = str.split(seperator);
   leftOver.forEach(left => {
      actual.splice(actual.indexOf(left), 1);
   })
   return actual;
}
console.log(returnSplittedArray(string, 5, " "));

Output

["over", "the", "wall"]
Updated on: 2020-08-18T06:55:16+05:30

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements