例如:将‘HELLO WORLD’转成‘hello world’。
方法一、根据字典项循环匹配(较笨)
let str = 'HELLO WORLD';
// 转小写
let dic = {
'A': 'a',
'B': 'b',
'C': 'c',
'D': 'd',
'E': 'e',
'F': 'f',
'G': 'g',
'H': 'h',
'I': 'i',
'J': 'j',
'K': 'k',
'L': 'l',
'M': 'm',
'N': 'n',
'O': 'o',
'P': 'p',
'Q': 'q',
'R': 'r',
'S': 's',
'T': 't',
'U': 'u',
'V': 'v',
'W': 'w',
'X': 'x',
'Y': 'y',
'Z': 'z'
}
// 循环遍历
let lowerStr = '';
for(let i = 0; i <= str.length; i++){
let item = str[i];
if (dic[item]){ // 字典中就匹配,不在就返回本身
lowerStr += dic[item];
} else {
lowerStr += item;
}
}
console.log(lowerStr); // 'hello world'
方法二:根据Unicode编码来找到大写字母对应的小写字母
let str = 'HELLO WORLD';
function handleLower (str = '') {
let codeStart = 'A'.charCodeAt();
let codeEnd = 'Z'.charCodeAt();
let codeLowerStart = 'a'.charCodeAt();
let minus = codeLowerStart - codeStart;
if (str) {
if (str.charCodeAt() < code || str.charCodeAt() > codeEnd) { // 处理非大写字母
return str;
}
return String.fromCharCode(str.charCodeAt() + minus);
}
return '';
}
let lowerStr = '';
for(let i = 0; i <= str.length; i++){
let item = str[i];
lowerStr += handleLower(item);
}
console.log(lowerStr); // hello world