javascript - 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()));
解决方案
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);
推荐阅读
- php - 检查 csv 中的列是否在给定的最大值中是 > 或 <
- azure - Dynamics CRM作为sink时如何在Azure数据工厂中实现动态列映射
- php - 在 PHP 中使用变量创建逗号分隔的链接列表
- javascript - 多折线图中的画笔仅适用于一条线
- php - 获取不在括号内的字符 REGEX
- ios - UIView 中的阴影无法覆盖 Xamarin 表单中的条目或编辑器或选取器
- php - 将 PHP 数组发布到需要 JSON 对象数组的 API 的问题
- php - 如何在核心 PHP 中使用 Laravel Eloquent 模型?
- javascript - onClick 在 React.js 中多次触发
- ios - 将 int 从字符串时间 4:01 快速递减到 3:51