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

การลบสระสุดท้ายของแต่ละคำ - JavaScript

ฟังก์ชันนี้ลบสระ (a, e, i, o, u) ตัวสุดท้ายของแต่ละคำในประโยค

ตัวอย่าง

// Input: 'This is an example string'
// Output: 'Ths s n exampl strng'

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

const str = 'This is an example string';

const removeLast = word => {
  const lastIndex = el => word.lastIndexOf(el);
  // หาตำแหน่งสระสุดท้าย (max ของ lastIndex ของทุกสระ)
  const ind = Math.max(
    lastIndex('a'), lastIndex('e'), lastIndex('i'),
    lastIndex('o'), lastIndex('u')
  );
  // ตัดตัวอักษรที่ตำแหน่ง ind ออก
  return word.substr(0, ind) + word.substr(ind + 1);
};

const removeLastVowel = str => {
  return str.split(' ')
    .map(removeLast)
    .join(' ');
};

console.log(removeLastVowel(str));

การทำงาน

  1. แยกคำด้วย split(' ')
  2. หาสระตัวสุดท้ายของแต่ละคำด้วย lastIndexOf
  3. ตัดตัวอักษรตำแหน่งนั้นออกด้วย substr
  4. รวมคำกลับด้วย join(' ')

ผลลัพธ์

Ths s n exampl strng