ภาพรวม
บทความนี้สาธิตวิธีลบสระ (Vowel: a, e, i, o, u) ตัวสุดท้ายของแต่ละคำในประโยค
ตัวอย่าง
Input: 'This is an example string'
Output: 'Ths s n exampl strng'
// This -> Ths (i ตัวสุดท้าย), is -> s (i), an -> n (a), example -> exampl (e), string -> strng (i)
การนำไปใช้
const removeLast = (word) => {
const lastIndex = (el) => word.lastIndexOf(el);
const ind = Math.max(
lastIndex('a'), lastIndex('e'), lastIndex('i'),
lastIndex('o'), lastIndex('u')
);
return word.slice(0, ind) + word.slice(ind + 1);
};
const removeLastVowel = (str) => {
return str.split(' ')
.map(removeLast)
.join(' ');
};
console.log(removeLastVowel('This is an example string'));
ผลลัพธ์
Ths s n exampl strng
วิธีการทันสมัยและครอบคลุมมากกว่า
const removeLastVowelModern = (str) => {
const vowels = new Set('aeiouAEIOU');
return str.split(' ').map(word => {
// หาสระตัวสุดท้าย (Case Insensitive)
for (let i = word.length - 1; i >= 0; i--) {
if (vowels.has(word[i])) {
return word.slice(0, i) + word.slice(i + 1);
}
}
return word; // ไม่มีสระ
}).join(' ');
};
// Regex Version (สั้นแต่อาจช้า)
const removeLastVowelRegex = (str) =>
str.replace(/\b(\w*?)([aeiouAEIOU])(\w*)\b/g, '$1$3');
การจัดการ Unicode (Thai Vowels)
const removeLastThaiVowel = (str) => {
// Thai Vowels: ะ, ำ, า, ิ, ี, ึ, ื, ุ, ู, เ, แ, โ, ใ, ไ
const thaiVowels = new Set('ะำาิีึืุูเแโใไ');
return str.split(' ').map(word => {
for (let i = word.length - 1; i >= 0; i--) {
if (thaiVowels.has(word[i])) {
return word.slice(0, i) + word.slice(i + 1);
}
}
return word;
}).join(' ');
};
การประยุกต์ใช้
- Word Games: Word Puzzles, Riddles
- Linguistics: Morphological Analysis
- Text Obfuscation
- Poetry: Constrained Writing