Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แทนที่คำใน String ด้วย JavaScript

โจทย์

สลับคำที่อยู่ติดกันใน string

Input: "This is a sample string only"
Output: "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

คำอธิบาย

split(" ") แยกคำเป็น array
reduce วนลูป index คู่ (0,2,4...) สลับตำแหน่งกับคำถัดไป (index+1)
arr[ind+1] || "" ป้องกัน index out of bounds สำหรับคำสุดท้ายถ้าจำนวนคำเป็นคี่
ผล: คำ 0↔1, 2↔3, 4↔5 สลับกัน