Viết hàm nhận chuỗi str và mảng từ arr. Bọc cặp thẻ <p></p> quanh các substring trong str khớp với từ trong arr. Gộp các thẻ chồng chéo hoặc liên tiếp.
Ví dụ: str='kkkllmm', arr=["kkk","kkl","lm"] → '<p>kkkllm</p>m'.
Ví dụ
const str = 'kkkllmm';
const arr = ["kkk","kkl","lm"];
var addParagraphTag = (str = [], arr = []) => {
if (!arr.length) return str;
const { length } = str;
let paraBoolean = new Array(length).fill(false);
let end = 0;
for (let i = 0; i < length; i++) {
for (let j = 0; j < arr.length; j++) {
let word = arr[j];
if (str.startsWith(word, i)) end = Math.max(end, i + word.length);
}
paraBoolean[i] = end > i;
}
let curr = 0, newStr = '';
while (curr < length) {
while (paraBoolean[curr] === false) newStr += str[curr++];
if (curr >= length) break;
newStr += '<p>';
let startBold = curr;
while (paraBoolean[curr] === true) curr++;
newStr += str.slice(startBold, curr);
newStr += '</p>';
}
return newStr;
};
console.log(addParagraphTag(str, arr));
Kết quả
<p>kkkllm</p>m