在JavaScript中,将字符串中的小写字母转换为大写字母可以使用内置的toUpperCase()
方法。这个方法会返回一个新的字符串,原字符串中的所有小写字母都会被转换为大写字母,而其他字符则保持不变。
let str = "hello world!";
let upperStr = str.toUpperCase();
console.log(upperStr); // 输出 "HELLO WORLD!"
toUpperCase()
方法不会改变原始字符串,而是返回一个新的字符串。如果你只想转换字符串中的部分字符为大写,可以结合使用其他字符串方法,如substring()
或正则表达式。
例如,将字符串中每个单词的首字母转换为大写:
function capitalizeFirstLetterOfEachWord(str) {
return str.replace(/\b\w/g, function(char) {
return char.toUpperCase();
});
}
let str = "hello world!";
let capitalizedStr = capitalizeFirstLetterOfEachWord(str);
console.log(capitalizedStr); // 输出 "Hello World!"
这个函数使用了正则表达式来匹配每个单词的首字母,并使用toUpperCase()
方法将其转换为大写。
领取专属 10元无门槛券
手把手带您无忧上云