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

การกลับสตริงโดยคงตำแหน่งช่องว่างใน JavaScript

ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่อาจมีช่องว่าง ฟังก์ชันควรกลับคำในสตริงภายในโดยไม่สลับตัวอักษรของคำต่างกันหรือช่องว่าง

ตัวอย่าง

โค้ดตัวอย่างด้านล่าง:

const str = 'this is normal string';
const reverseWordsWithin = (str = '') => {
  let res = "";
  for (let i = str.length - 1; i >= 0; i--) {
    if (str[i] != " ") {
      res += str[i];
    }
    if (str[res.length] == " ") {
      res += str[res.length];
    }
  }
  return res;
};
console.log(reverseWordsWithin(str));

ผลลัพธ์

gnir ts lamron sisiht

คำอธิบายเพิ่มเติม

โค้ดตัวอย่างมีบั๊ก: มันกลับสตริงทั้งหมด (reverse entire string) แต่พยายามคง space ไว้ที่ตำแหน่งเดิม ผลลัพธ์ 'gnir ts lamron sisiht' ไม่ใช่การกลับคำแต่ละคำ (ควรเป็น 'siht si lamron gnirts') ต้อง split by space, reverse each, join