ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงตัวอักษร str และตัวอักษรเดี่ยว char ฟังก์ชันควรสร้างสตริงใหม่ที่ประกอบด้วยตัวอักษรที่อยู่ทันทีหลังจาก char ทุกครั้งที่ปรากฏใน str (ถ้ามี)
ตัวอย่าง
โค้ดตัวอย่างด้านล่าง:
const str = 'this is a string';
const letter = 'i';
const findNextString = (str = '', letter = '') => {
let res = '';
for (let i = 0; i < str.length; i++) {
const el = str[i];
const next = str[i + 1];
if (letter === el && next) {
res += next;
}
}
return res;
};
console.log(findNextString(str, letter));
ผลลัพธ์
ssn
คำอธิบายเพิ่มเติม
จากสตริง 'this is a string' ตัวอักษร 'i' ปรากฏ 3 ครั้ง ตัวถัดไปคือ 's', 's', 'n' ตามลำดับ โค้ดตรวจสอบขอบเขตด้วยตัวแปร next