Skip to content

Commit 96e7282

Browse files
committed
update Candy-015
1 parent 9a03582 commit 96e7282

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Candy-015/README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
## 編號:CANDY-015
2+
3+
### 程式語言:JavaScript
4+
5+
#### 題目:把原本的字串拆解成 2 個字元一組,若不足 2 個字則補上底線
6+
7+
範例:
8+
9+
```js
10+
"abcdef" -> ['ab', 'cd', 'ef']
11+
"abcdefg" -> ['ab', 'cd', 'ef', 'g_']
12+
```
13+
14+
```js
15+
function splitString(str) {
16+
if (str === "") return [];
17+
return (str.length % 2 == 0 ? str : str + "_").match(/.{2}/g);
18+
}
19+
20+
// 判斷字串是空字串時回傳空陣列
21+
// 如果不是空字串時, 字串取 2 的餘數為 0 回傳原本的陣列
22+
// 如果不為 0, 表示有字串是單獨的則在字串後面加 "_"
23+
// 最後使用 match() 並搭配正規表達式, 表示 \n 跟 \r 以外的單個字元
24+
// \n 是換行符, \r 是回車字元, {2} 為符合 2 次, /g 為全局匹配
25+
26+
console.log(splitString("abcdef")); // ["ab", "cd", "ef"]
27+
console.log(splitString("abcdefg")); // ["ab", "cd", "ef", "g_"]
28+
console.log(splitString("")); // []
29+
```

0 commit comments

Comments
 (0)