# [Codewars - 6kyu解題] Replace With Alphabet Position 字母替換成數字
###### tags: `Codewars`,`6kyu`,`Javascript`,`Array`,`.forEach()`,`ifelse in forEach()`,`.charCodeAt()`,`.match()`,`RegExp`
> Javascript菜鳥紀錄Codewars解題過程
## Instructions 題目
:link: https://www.codewars.com/kata/546f922b54af40e1e90001da
:pushpin: **Instructions:**
接收一組字串,並按序回傳字母所代表的數字("a" = 1, "b" = 2, etc),若不是字母的話則忽略不回傳。
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
:bulb: **Examples:**
alphabetPosition("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (as a string)
## My Solution 我的解法
```javascript=
function alphabetPosition(text) {
var str = []
var res = []
text.split('').forEach(i => str.push(i.charCodeAt()));
str.forEach(item => {
if(item>=65&&item<=90){
res.push(item-64);}
else if(item>=97&&item<=122){
res.push(item-96);}
else{}
});
return res.join(' ');
}
```
## Solutions(1) 其他更精簡的寫法
```javascript=
function alphabetPosition(text) {
return text
.toUpperCase()
.match(/[a-z]/gi)
.map( (c) => c.charCodeAt() - 64)
.join(' ');
}
```
## Solutions(2) 其他更精簡的寫法
```javascript=
function alphabetPosition(text) {
return text.match(/[a-zA-Z]/g)
.map( (el) => el.toLowerCase().charCodeAt() - 96 ).join(' ');
}
```
## :memo: 學習筆記
:bulb: **If else in foreach**
https://stackoverflow.com/questions/50528628/if-else-in-foreach
>
> forEach()內使用if/else 判斷式的寫法。
>
```javascript=
arr.forEach(element => {
if(element.key === 'first') {
// do something
} else {
// do something else
}
if(element.key === 'second') {
// do something
} else {
// do something else
}
});
```
---
:bulb: **Switch...case...break**
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/switch
> switch 會比對一個 表達式 裡頭的值是否符合 case 條件,然後執行跟這個條件相關的 陳述式, 以及此一符合條件以外,剩下其他條件裡的陳述式。
>
> 一個 switch 陳述式會先評估自己的 expression。然後他會按照 case 條件順序開始尋找,直到比對到第一個表達式值跟輸入 expression 的值相等的 case 條件(使用嚴格的邏輯運算子, ===)並把控制流交給該子句、並執行裡面的陳述式
>
> **switch 一般只在多條件判斷使用,但無法像if/else使用運算式進行判斷。**
---
:bulb: **.match(/[aeiou]/gi)**
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/String/match
>
> 用.match( ) 方法,結合正規表示式進行比對
> 找出陣列元素符合a、e、i、o、u,全域比對,忽略大小寫
>
:bulb: **正規表示式RegExp**
http://syunguo.blogspot.com/2013/04/jsregular-expressions.html
https://felixhuang.pixnet.net/blog/post/23673013-%5Bjavascript%5D-%E6%AD%A3%E8%A6%8F%E5%8C%96%E8%A1%A8%E7%A4%BA%E6%B3%95%E9%80%9F%E6%9F%A5%E8%A1%A8
https://atedev.wordpress.com/2007/11/23/%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%A4%BA%E5%BC%8F-regular-expression/