根據條件更改字串 - JavaScript
我們需要編寫一個 JavaScript 函式,該函式接受一個字串作為輸入。我們的函式的任務是根據以下條件更改字串 -
- 如果字串的第一個字母是大寫字母,則我們應該將整個字串更改為大寫字母。
- 否則,我們應該將整個字串更改為小寫字母。
示例
以下為程式碼 -
const str1 = "This is a normal string"; const str2 = "thisIsACamelCasedString"; const changeStringCase = str => { let newStr = ''; const isUpperCase = str[0].charCodeAt(0) >= 65 && str[0].charCodeAt(0) <= 90; if(isUpperCase){ newStr = str.toUpperCase(); }else{ newStr = str.toLowerCase(); }; return newStr; }; console.log(changeStringCase(str1)); console.log(changeStringCase(str2));
輸出
以下是控制檯中的輸出 -
THIS IS A NORMAL STRING thisisacamelcasedstring
廣告