Viết hàm nhận chuỗi, trả về chuỗi mới với nguyên âm cuối cùng của mỗi từ bị loại bỏ.
Ví dụ
Đầu vào: 'This is an example string'
Đầu ra: 'Ths s n exampl strng'
- This → Ths (bỏ 'i')
- is → s (bỏ 'i')
- an → n (bỏ 'a')
- example → exampl (bỏ 'e')
- string → strng (bỏ 'i')
Giải pháp
Mã triển khai:
const str = 'This is an example string';
const removeLastVowel = word => {
const vowels = 'aeiouAEIOU';
let lastVowelIndex = -1;
for (let i = word.length - 1; i >= 0; i--) {
if (vowels.includes(word[i])) {
lastVowelIndex = i;
break;
}
}
if (lastVowelIndex === -1) return word;
return word.slice(0, lastVowelIndex) + word.slice(lastVowelIndex + 1);
};
const removeLastVowelFromString = str =>
str.split(' ').map(removeLastVowel).join(' ');
console.log(removeLastVowelFromString(str));
Kết quả
Đầu ra trong console:
Ths s n exampl strng