Vấn đề
Chúng ta cần viết một hàm JavaScript nằm trên đối tượng prototype của lớp String. Hàm này đơn giản thay đổi chữ cái của tất cả các chữ cái trong chuỗi thành chữ hoa và trả về chuỗi mới.
Ví dụ
Dưới đây là mã nguồn:
const str = 'This is a lowercase String';
String.prototype.customToUpperCase = function(){
const legend = 'abcdefghijklmnopqrstuvwxyz';
const UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let res = '';
for(let i = 0; i < this.length; i++){
const el = this[i];
const index = legend.indexOf(el);
if(index !== -1){
res += UPPER[index];
}else{
res += el;
};
};
return res;
};
console.log(str.customToUpperCase());Kết quả
Kết quả đầu ra trong console:
THIS IS A LOWERCASE STRING