Convert PascalCase string into snake_case
5 kyu
- 題目描述
- 解答
Description
Complete the function/method so that it takes a PascalCase string and returns the string in snake_case notation. Lowercase characters can be numbers. If the method gets a number as input, it should return a string.
Examples
"TestController" --> "test_controller"
"MoviesAndBooks" --> "movies_and_books"
"App7Test" --> "app7_test"
1 --> "1"
Solution
function toUnderscore(string) {
if (typeof string === "number") return string.toString();
return string
.replace(/([A-Z])/g, "_$1")
.replace(/^_/, "")
.toLowerCase();
}
解題思路
按照題目描述若是數字的話直接回傳,接著使用$1判斷找到的大寫字母,把所有大寫字母前加底線 _ ,並移除開頭的 底線 _ ,最後通通轉小寫回傳轉換後的結果。
心得
練習正則表達式與使用 replace() 來更新字串。
.replace(/([A-Z])/g, "_$1")
/g 代表 global,確保符合的所有大寫字母都會被替換,而不只是第一個。
$1 代表第一個找到的大寫字母。