Kata Practice - Disemvowel Trolls (JavaScript)

Kata Practice - Disemvowel Trolls (JavaScript)

這個系列會把自己練習過的 Kata 題目記錄下來,希望除了記錄的性質以外也能夠觀察自己撰寫程式邏輯的進化過程。如果有幸看到這邊的話也可以參考一下,再到 Codewars 的網站註冊一個帳號試著玩看看,自己蠻喜歡整個網站的得分和排行榜設定,會讓人越寫越有成就感喔!

題目

Trolls are attacking your comment section!

A common way to deal with this situation is to remove all of the vowels from the trolls’ comments, neutralizing the threat.

Your task is to write a function that takes a string and return a new string with all vowels removed.

For example, the string “This website is for losers LOL!” would become “Ths wbst s fr lsrs LL!”.

Note: for this kata y isn’t considered a vowel.

自己的解法

1
2
3
disemvowel = (str) => {
return str.replace(/[aeiou]/gi, '');
}

解題脈絡

這次一樣沒有想出來要怎麼解決,所以用了 claude 來詢問解法。所以使用正規表達式來找符合條件的字母並移除。

其他人的解法

1
2
3
4
5
6
7
8
const vowels = 'aeiou';

function disemvowel(str) {
return str
.split('')
.filter(letter => !vowels.includes(letter.toLowerCase()))
.join('');
}

選擇記錄這個解法的原因

我最一開始的想法是像之前一樣先把傳進來的字串使用 split 分開後在移除指定的母音大小寫,所以這個解法算是我可能自己寫出來的話會有的結果。
只是這個解法中直接將字串內的每一個 letter 使用 toLowerCase 的方法後就可以不用管大小寫,做一次的判斷就好了!

觀念釐清

雖然使用正規表達式的解法比較多,可是我是覺得如果你有透過 JavaScript 的字串 function 處理的話,會比較知道能達成題目需要的結果。
因為正規表達式其實比較像是語法糖,方法簡單很多而且需要的時候再去查我覺得就可以了。

那我們就下次見ʘ‿ʘ

評論