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

การกลับลำดับสระในสตริงด้วย JavaScript


ภาพรวม

เราต้องเขียนฟังก์ชันที่รับสตริงและกลับลำดับเฉพาะสระในสตริงนั้น

ตัวอย่าง

อินพุต: const str = 'Hello';

เอาต์พุต: const output = 'Holle';

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

const str = 'Hello';

const reverseVowels = (str = '') => {
  const vowels = new Set(['a','e','i','o','u','A','E','I','O','U']);
  let left = 0, right = str.length - 1;
  let foundLeft = false, foundRight = false;
  str = str.split("");
  
  while(left < right) {
    if(vowels.has(str[left])) {
      foundLeft = true;
    }
    if(vowels.has(str[right])) {
      foundRight = true;
    }
    if(foundLeft && foundRight) {
      [str[left], str[right]] = [str[right], str[left]];
      foundLeft = false;
      foundRight = false;
    }
    if(!foundLeft) {
      left++;
    }
    if(!foundRight) {
      right--;
    }
  }
  return str.join("");
};

console.log(reverseVowels(str));

ผลลัพธ์ในคอนโซล

Holle