在 JavaScript 中將混合大小寫字串轉換為小寫
問題
我們需要編寫一個 JavaScript 函式 convertToLower(),該函式採用字串方法,將呼叫該方法的字串轉換為小寫字串並返回新字串。
例如,如果函式的輸入為
輸入
const str = 'ABcD123';
輸出
const output = 'abcd123';
示例
以下為程式碼 −
const str = 'ABcD123'; String.prototype.convertToLower = function(){ let res = ''; for(let i = 0; i < this.length; i++){ const el = this[i]; const code = el.charCodeAt(0); if(code >= 65 && code <= 90){ res += String.fromCharCode(code + 32); }else{ res += el; }; }; return res; }; console.log(str.convertToLower());
輸出
abcd123
廣告