高级前端
js
【Q638】如何把字符串全部转化为小写格式

如何把字符串全部转化为小写格式

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 656 (opens in a new tab)

Author 回答者: cyio (opens in a new tab)

const convert = (str) => str.replace(/[A-Z]/g, (l) => l.toLowerCase());
 
// test
convert("aCd");
convert("aCd123");

Author 回答者: shfshanyue (opens in a new tab)

在 ES6+ 中,可直接使用原生 API String.prototype.toLowerCase() 实现

如果手写实现,如下所示

const lowerCase = (str) => {
  let result = "";
  for (let char of str) {
    const charAt = char.charCodeAt();
    if (charAt <= "Z".charCodeAt() && charAt >= "A".charCodeAt()) {
      char = String.fromCharCode(charAt + 32);
    }
    result += char;
  }
  return result;
};
 
//=> 'hello'
lowerCase("HELLO");
 
//=> '山月'
lowerCase("山月");

Author 回答者: shfshanyue (opens in a new tab)

const convert = (str) => str.replace(/[A-Z]/g, (l) => l.toLowerCase());
 
// test
convert("aCd");
convert("aCd123");

如果不使用 API 如何做

Author 回答者: Asarua (opens in a new tab)

不使用API是指什么

const convert = (str) => str.replace(/[A-Z]/g, (l) => l.toLowerCase());
 
// test
convert("aCd");
convert("aCd123");

如果不使用 API 如何做

Author 回答者: shfshanyue (opens in a new tab)

@Asarua 就是 toLowerCase

Author 回答者: Asarua (opens in a new tab)

@Asarua 就是 toLowerCase

原来如此,那还好,我以为不让用字符串所有的api