首页 > 解决方案 > str.toUpperCase() 在某些情况下无法将第一个字符转换为大写

问题描述

我在 JavaScript 中尝试了以下代码:

console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));

案例 1 - str = '变量':

const str = 'variable';
console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));

它给出了预期的输出,即'Variable',即字符串的第一个字母是大写的。

案例 2 - str = '变量':

const str = 'Variable';
console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));

它给出了一个奇怪的输出- 'variable'

我对 JavaScript 很陌生,无法理解这种行为的原因。

const str = 'Variable';
console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));

标签: javascriptstring

解决方案


str是一个常量和一个字符串(字符串是不可变的);它总是

const str = 'Variable';

如果你拿str[0],你得到V

因此,.toLowerCase().trim().replace(str[0]如果第一个字符是大写的,则永远不会匹配,因为大写str[0]不会包含在修剪后的小写字符串中。

我首先将字符串的小写版本保存在一个变量中,这样您就可以访问字符串的[0].

const str = 'Variable';
const lower = str.toLowerCase().trim();
console.log(lower.replace(lower[0], lower[0].toUpperCase()));

或者,更准确地说,只提取第一个字符,将其大写,其余部分小写。

const str = 'Variable';
const result = (
  str[0].toUpperCase() +
  str.slice(1).toLowerCase()
);
console.log(result);


推荐阅读