Chúng ta cần viết một hàm JavaScript nhận vào một chuỗi chứa văn bản đoạn làm đối số thứ nhất và một số kích thước khối làm đối số thứ hai. Hàm nên làm những việc sau:
- Chia chuỗi thành các khối có độ dài không vượt quá kích thước khối (đối số thứ hai),
- Việc chia chỉ xảy ra ở khoảng trắng hoặc cuối câu (không ngắt từ).
Ví dụ: Nếu chuỗi đầu vào là:
const str = 'this is a string'; const chunkLength = 6;
Thì đầu ra sẽ là:
const output = ['this', 'is a', 'string'];
Chúng ta sẽ sử dụng biểu thức chính quy để khớp số ký tự được chỉ định. Khi khớp, chúng ta sẽ lùi lại cho đến khi tìm thấy khoảng trắng hoặc cuối chuỗi.
Ví dụ
Code cho việc này sẽ là:
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));Kết quả
Kết quả hiển thị trong console sẽ là:
[ '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.' ]