เราต้องเขียนฟังก์ชันที่รับสตริงยาวและขนาดบล็อก (chunk size) แบ่งสตริงเป็นชิ้นๆ ไม่เกินขนาดที่กำหนด โดยตัดเฉพาะที่ช่องว่างหรือจบประโยค (ไม่ตัดคำ)
ใช้ Regular Expression เพื่อจับคู่จำนวนตัวอักษรที่กำหนด แล้วย้อนกลับหาช่องว่างหรือจบสตริง
ตัวอย่างโค้ด
const size = 200;
const str = "This process was continued for several years for the deaf child does not here in a month or even in two or three years the numberless items and expressions using the simplest daily intercourse little hearing child learns from these constant rotation and imitation the conversation he hears in his home simulates is mine and suggest topics and called forth the spontaneous expression of his own thoughts.";
const splitString = (str = '', size) => {
const regex = new RegExp(String.raw`\S.{1,${size - 2}}\S(?= |$)`, 'g');
const chunks = str.match(regex);
return chunks;
};
console.log(splitString(str, size));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
[ 'This process was continued for several years for the deaf child does not here in a month or even in two or three years the numberless items and expressions using the simplest daily intercourse little', 'hearing child learns from these constant rotation and imitation the conversation he hears in his home simulates is mine and suggest topics and called forth the spontaneous expression of his own', 'thoughts.' ]