Xóa nguyên âm cuối cùng của mỗi từ trong chuỗi JavaScript
Chúng ta cần viết một hàm JavaScript nhận vào một chuỗi và trả về chuỗi mới với nguyên âm cuối cùng của mỗi từ bị xóa.
Ví dụ: Nếu chuỗi là:
const str = 'This is an example string';
Thì kết quả đầu ra nên là:
const output = 'Ths s n exampl strng';
Do đó, hãy viết mã cho hàm này:
Ví dụ
Mã thực hiện như sau:
const str = 'This is an example string';
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.substr(0, ind) + word.substr(ind+1, word.length);
}
const removeLastVowel = str => {
const strArr = str.split(' ');
return strArr.reduce((acc, val) => {
return acc.concat(removeLast(val));
}, []).join(' ');
};
console.log(removeLastVowel(str));
Đầu ra
Kết quả trong console sẽ là:
Ths s n exampl strng