Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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"]
Advertisements
