在JavaScript中处理字符串时,你可以对它们进行不同的操作。
你可能对字符串进行的操作包括大写、转换为小写、在单词中添加符号,以及更多。
在这篇文章中,我将向你展示如何用.toUpperCase() 字符串方法将一个字符串转换为大写字母。
.toUpperCase() 方法的基本语法
要使用.toUpperCase() 方法,请将你想改成大写的字符串分配给一个变量,然后在其前面加上.toUpperCase() 。
如何用.toUpperCase将一个字符串大写化
如前所述,你可以将一个字符串分配给一个变量,然后使用.toUpperCase() 方法将其大写。
const name = "freeCodeCamp";
const uppercase = name.toUpperCase();
console.log(uppercase);
// Output: FREECODECAMP
你也可以写一个函数,并在其中返回.toUpperCase() ,这样,当函数被调用时,一个声明的参数就会被大写。
function changeToUpperCase(founder) {
return founder.toUpperCase();
}
// calling the function
const result = changeToUpperCase("Quincy Larson");
// printing the result to the console
console.log(result);
// Output: QUINCY LARSON
在上面的脚本中。
- 我定义了一个名为
changeToUpperCase的函数,其占位符为founder - 我告诉该函数,我想让它做的是,当我调用它时,将我指定的任何参数改为大写字母。
- 然后,我将函数调用--
changeToUpperCase分配给了一个名为 "A "的变量。result - 在该变量的帮助下,我能够将该函数的结果打印到控制台。
结论
当你需要在你的JavaScript项目中对字符串进行大写时,你可以使用.toUpperCase() 方法,全称是String.prototype.toUpperCase() 。