เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงอักขระเป็นอาร์กิวเมนต์แรก และดัชนีเริ่มต้นและดัชนีสิ้นสุดเป็นอาร์กิวเมนต์ที่สองและสามตามลำดับ ฟังก์ชันควรค้นหา หากสตริงนั้น ซึ่งระบุเป็นอาร์กิวเมนต์แรก ถูกขยายตลอดไปโดยต่อท้ายสตริงเดียวกันเมื่อสิ้นสุดแต่ละครั้ง สิ่งที่จะเป็นสตริงย่อยที่ห่อหุ้มด้วยดัชนีเริ่มต้นและดัชนีสิ้นสุด
ตัวอย่างเช่น −
หากสตริงอินพุตและดัชนีเป็น −
const str = 'helloo'; const start = 11; const end = 15;
จากนั้นผลลัพธ์ควรเป็น −
const output = 'hel';
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = 'helloo';
const start = 12;
const end = 15;
const findSubstring = (str = '', start, end) => {
let n = str.length;
let t = start / n;
start = start % n;
end -= t * n;
let res = str.substring(start, end - start);
if (end > n){
t = (end - n) / n;
end = (end - n) - t * n;
while (t --) {
res += str;
}
res += str.substring(0, end);
};
return res;
};
console.log(findSubstring(str, start, end)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
hel