【JS字符串】toLowerCase – 返回所有字符都转换为小写的字符串

JavaScript字符串1年前 (2023)更新 admin
1,971 0

在本教程中,您将学习如何使用 JavaScript String.prototype.toLowerCase() 方法返回一个所有字符都转换为小写的字符串。

JavaScript toLowerCase() 方法介绍

toLowerCase() 方法返回一个所有字符都转换为小写的新字符串。 下面显示了 toLowerCase() 方法的语法:

str.toLowerCase()

例如:

const message = ‘Hi’;
const newMessage = message.toLowerCase();

console.log(newMessage);

输出:

hi

因为字符串是不可变的,所以 toLowerCase() 方法不会更改原始字符串。 相反,它返回一个所有字符都转换为小写的新字符串。

在 null 或 undefined 上调用 JavaScript toLowerCase() 方法

如果在 null 或 undefined 上调用 toLowerCase() 方法,该方法将抛出 TypeError 异常。

如果 id 大于零或 null,则以下 findUserById 函数返回一个字符串:

const findUserById = (id) => {
if (id > 0) {
// look up the user from the database
// …
//
return ‘admin’;
}
return null;
};

如果您对 findUserById() 函数的结果调用 toLowerCase() 方法,当 id 为零或负数时,您将得到 TypeError:

console.log(findUserById(-1).toLowerCase());

错误:

TypeError: Cannot read properties of null (reading ‘toLowerCase’)

为了安全起见,您可以使用可选的链接运算符 ?。 如下:

console.log(findUserById(-1)?.toLowerCase());

输出:

undefined

将非字符串转换为字符串

如果将其 this 值设置为非字符串值,则 toLowerCase() 方法会将非字符串值转换为字符串。

例如:

const user = {
username: ‘JOE’,
toString() {
return this.username;
},
};

const username = String.prototype.toLowerCase.call(user);
console.log(username);

输出:

joe

在此示例中,我们通过使用 call() 方法调用 toLowerCase() 方法并将 this 设置为用户对象。 toLowerCase() 方法通过调用其 toString() 方法将用户对象转换为字符串。

总结

使用 toLowerCase() 方法返回所有字符都转换为小写的字符串。

© 版权声明

相关文章

暂无评论

暂无评论...