在 JavaScript 中将字符串转换为小写

57 阅读1分钟

要将字符串转换为小写,在 JavaScript 中,我们可以使用内置的 toLowerCase() 方法。

以下是将字符串 How ARE YOU 转换为小写的示例。

const message = "How ARE YOU";

const lowercaseMsg = message.toLowerCase();

console.log(lowercaseMsg);

输出结果:

'how are you'

如何将字符串的第一个字母转换为小写呢?

要将第一个字母转换为小写,我们需要使用 charAt() 方法获取字符串的第一个字母,然后将其连接到 toLowerCase 方法上,并通过切片操作将第一个字母与字符串连接起来。

const name = "JAVASCRIPT";

console.log( name.charAt(0).toLowerCase()+name.slice(1));

// "jAVASCRIPT"

注意:toLowerCase 方法不会改变原始字符串,它返回一个新的字符串,其中包含小写字母。