เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและแทนที่คำที่อยู่ติดกันของสตริงนั้น
ตัวอย่างเช่น หากสตริงอินพุตคือ −
const str = "This is a sample string only";
จากนั้นผลลัพธ์ควรเป็น −
"is This sample a only string"
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = "This is a sample string only";
const replaceWords = str => {
return str.split(" ").reduce((acc, val, ind, arr) => {
if(ind % 2 === 1){
return acc;
}
acc += ((arr[ind+1] || "") + " " + val + " ");
return acc;
}, "");
};
console.log(replaceWords(str)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
is This sample a only string