공식 String.prototype.split() 메서드에는 인덱스 1에서 또는 일반적으로 인덱스 n에서 문자열 분할을 시작할 방법이 없지만 split()을 사용하는 방식을 약간 조정하면 이 기능을 얻을 수 있습니다.
우리는 다음과 같은 접근 방식을 따랐습니다 -
우리는 두 개의 배열을 만들 것입니다 -
- 0에서 끝까지 분할된 것 --- ACTUAL
- 0에서 TO STARTPOSITION --- LEFTOVER까지 분할된 초
이제 남은 요소의 각 요소를 반복하고 실제 배열에서 연결합니다. 따라서 실제 배열은 가상적으로 STARTINDEX에서 END로 분할됩니다.
예시
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, " "));
출력
["over", "the", "wall"]