มีสองวิธีในการแบ่งสตริงขนาดใหญ่เป็นสตริงย่อยขนาด n
1) วิธีการทั่วไป
นี่เป็นวิธีลอจิกล้วนๆ ที่ใช้เฉพาะวิธีการทั่วไป เช่น for loop, concat, modulous เป็นต้น วิธีนี้ไม่ได้ซับซ้อนเท่าวิธี regex เพราะเป็นวิธีการที่กำหนดไว้ล่วงหน้า ควรกำหนดจำนวนชิ้นที่จะแบ่งสตริงก่อนเริ่มการเข้ารหัส
ในตัวอย่างต่อไปนี้ สตริง "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
ไม่ใช่วิธีการที่กำหนดไว้ล่วงหน้า วิธี 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>