摘要:在本教程中,您将学习如何使用 JavaScript String.prototype.toLowerCase() 方法返回一个所有字符都转换为小写的新字符串。
JavaScript toLowerCase() 方法简介
toLowerCase() 方法返回一个所有字符都转换为小写的新字符串。以下显示了 toLowerCase() 方法的语法
str.toLowerCase()Code language: CSS (css)例如
const message = 'Hi';
const newMessage = message.toLowerCase();
console.log(newMessage);Code language: JavaScript (javascript)输出
hi由于字符串是不可变的,toLowerCase() 方法不会改变原始字符串。相反,它返回一个所有字符都转换为小写的新字符串。
对 null 或 undefined 调用 JavaScript toLowerCase() 方法
如果您对 null 或 undefined 调用 toLowerCase() 方法,该方法将 抛出 TypeError 异常。
以下 findUserById 函数在 id 大于零时返回字符串,否则返回 null
const findUserById = (id) => {
if (id > 0) {
// look up the user from the database
// ...
//
return 'admin';
}
return null;
};Code language: JavaScript (javascript)如果您对 findUserById() 函数的结果调用 toLowerCase() 方法,当 id 为零或负数时,您将获得 TypeError
console.log(findUserById(-1).toLowerCase());Code language: CSS (css)错误
TypeError: Cannot read properties of null (reading 'toLowerCase')Code language: JavaScript (javascript)为了安全起见,您可以使用 可选链运算符 ?.,如下所示
console.log(findUserById(-1)?.toLowerCase());Code language: CSS (css)输出
undefinedCode language: JavaScript (javascript)将非字符串转换为字符串
如果您将 this 值设置为非字符串值,toLowerCase() 方法将把非字符串值转换为字符串。例如
const user = {
username: 'JOE',
toString() {
return this.username;
},
};
const username = String.prototype.toLowerCase.call(user);
console.log(username);
Code language: JavaScript (javascript)输出
joe在此示例中,我们使用 call() 方法调用 toLowerCase() 方法,并将 this 设置为 user 对象。toLowerCase() 方法通过调用其 toString() 方法将 user 对象转换为字符串。
总结
- 使用
toLowerCase()方法返回一个所有字符都转换为小写的新字符串。
本教程对您有帮助吗?