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

วิธีเพิ่มตัวอักษรหน้าทุกคำในสตริงใน JavaScript

เราต้องเขียนฟังก์ชันรับสองสตริง คืนสตริงใหม่เหมือนอาร์กิวเมนต์แรก แต่มีอาร์กิวเมนต์ที่สองต่อหน้าทุกคำ

เช่น

Input → 'hello stranger, how are you', '@@'
Output → '@@hello @@stranger, @@how @@are @@you'

ถ้าไม่ระบุอาร์กิวเมนต์ที่สอง ใช้ '#' เป็นค่าเริ่มต้น

ตัวอย่าง

const str = 'hello stranger, how are you';
const prependString = (str, text = '#') => {
  return str
    .split(" ")
    .map(word => `${text}${word}`)
      .join(" ");
};
console.log(prependString(str));
console.log(prependString(str, '43'));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็น

#hello #stranger, #how #are #you
43hello 43stranger, 43how 43are 43you