큰 문자열을 n 크기의 하위 문자열로 분할하는 두 가지 방법이 있습니다.
1) 기존 방식
이것은 for loop, concat, modulous 등과 같은 기존의 방법만 사용하는 순수한 논리 방법입니다. 이 방법은 미리 결정된 방법이기 때문에 정규식 방법만큼 정교하지 않습니다. 분할할 문자열의 청크 수는 코딩을 시작하기 전에 미리 결정되어야 합니다.
다음 예에서 "tutorixtutorixtutorix" 문자열은 3개의 하위 문자열로 나뉩니다.
예시
<html> <body> <script> var v = []; var str = "tutorixtutorixtutorix" var t = str.split(""); document.write(t); document.write("</br>"); for (var i = 0; i< t.length; i++){ if((i % 3) == 2){ v.push(t[i-2].concat(t[i-1],t[i])); } } document.write(v); </script> </body> </html>
출력
tut,ori,xtu,tor,ixt,uto,rix
2) 정규식 메소드
미리 정해진 방법이 아닙니다. Regex 메서드는 문자열을 청크할 크기를 언급하는 슬롯을 제공합니다.
일반적으로 최대 n 크기의 하위 문자열을 추출하려는 문자열의 경우 구문은 다음과 같습니다.
str.match(/.{1,n}/g); // Replace n with the size of the substring
문자열에 개행 또는 캐리지 리턴이 포함된 경우 구문은
str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring
코드의 원래 구문은
function chunkString(str, size) { return str.match(new RegExp('.{1,' + size + '}', 'g')); }
예시
<html> <body> <script> stringChop = function(str, size){ if (str == null) return []; str = String(str); return size > 0 ? str.match(new RegExp('.{1,' + size + '}', 'g')) : [str]; } document.write(stringChop('tutorialspoint')); document.write("<br>"); document.write(stringChop('tutorix',2)); document.write("<br>"); document.write(stringChop('tutorialspoint',3)); </script> </body> </html>