iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 2
0
自我挑戰組

菜鳥工程師的奇幻漂流:跟著kata活化手指和意識系列 第 2

Vowel Count

今日kata

原始題目如下:(7kyu)
Return the number (count) of vowels in the given string.
We will consider a, e, i, o, u as vowels for this Kata (but not y).
The input string will only consist of lower case letters and/or spaces.

翻譯:
找出字串中a,e,i,o,u的個數

範例:
getCount("o a kak ushakov lil vo kashu kakao")->回傳 13
getCount("pear tree")->回傳 4


構想&解法

function getCount(str) {
  let wordMatch=['a','e','i','o','u'];
  return str.split('').filter(item=>wordMatch.includes(item)).length
}

str為輸入的字串,a,e,i,o,u是要搜尋的特定字元。

將str轉為array,使用filter遍歷每一個元素去過濾,過濾條件則是:目前元素是否為a,e,i,o,u其中之一。

將搜尋字元a,e,i,o,u存入陣列中,使用arr.includes()回傳true/false,判斷是否留下該元素。


其他解法觀摩

function getCount(str) {
  return (str.match(/[aeiou]/ig)||[]).length;
}

使用match留下符合regex的結果


function getCount(str) {
  return str.replace(/[^aeiou]/gi, '').length;
}

使用replace將非aeiou的字元消除,結果一樣是留下aeiou的字元


function getCount(str) {
 return str.split('').filter(c => "aeiouAEIOU".includes(c)).length;
}

類似自己原先寫法,又再更簡潔!! 不再額外宣告一個變數儲存aeiou


整理用法

陣列.includes()

語法: arr.includes(searchElement[, fromIndex])

搜尋Array的每一個元素,判斷是否包含searchElement,回傳True or False。fromIndex為陣列開始搜尋的位置。

範例:

['a','e','i','o','u'].includes('a')
// true

['a','e','i','o','u'].includes('x')
// false

['a','e','i','o','u'].includes('a',1)
// fasle (fromIndex=1 代表從陣列位置1的元素開始往後搜尋)

字串.split()

語法: str.split([separator[, limit]])

依指定分隔符號拆解str,結果是以陣列形式回傳,可傳入limit指定輸出前幾個元素。

範例:

let str='apple'
let splits = str.split('')
// splits= ['a','p','p','l','e']
// str本身不會被異動

let splits = str.split('',2)
// splits=['a','p'] 
// 回傳結果陣列的前兩個元素

字串.match()

語法:str.match(regexp)

需傳入RegExp物件,如果傳入obj的不是RegExp物件,會自動轉換成傳入new RegExp(obj)
若有使用g flag(代表global搜尋),以陣列方式回傳,str中符合正規表示式的所有字串。
若沒有使用g flag,以陣列方式回傳,第一個符合的字串。

範例:

let str='I love coding';
const regex=/o/g;
console.log(str.match(regex));
//['o','o']

字串.replace()

語法:str.replace(regexp|substr, newSubstr|function)

需傳入兩個參數:
1.搜尋的字串或正規表示式
2.要替換成的新字串或執行的函式

結果會回傳一個新的字串。

範例:

let str='I don\'t love coding'
console.log(str.replace('don\'t ','love'))
// I love coding

以上為今日分享的內容,若有錯誤或是建議,請再隨時和我聯繫。


上一篇
菜鳥工程師的奇幻漂流之前言
下一篇
Get the mean of an array
系列文
菜鳥工程師的奇幻漂流:跟著kata活化手指和意識30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言