String in JavaScript is a sequence of characters. And capitalizing characters of words in a JavaScript string will change each character of the string with the capital letter of it.
JavaScript中的字符串是字符序列。 而将JavaScript字符串中的单词大写会更改字符串中每个大写字母的字符。
To convert words to uppercase we have the following method defined by slicing each character and then converting it to uppercase.
要将单词转换为大写,我们可以通过对每个字符进行切片然后将其转换为大写来定义以下方法。
Components are defined as:
组件定义为:
Slice():
The slice method will return the specified element of the object and returns it to another object.
片():
slice方法将返回对象的指定元素,并将其返回到另一个对象。
For slice(3) for the array [3,5,6,8,9] will give 8.
对于数组[3,5,6,8,9]的slice(3)将得到8。
toUpperCase():
The method will return the uppercase changed the value of the character. For example: for 'f' input, the output is 'F'.
toUpperCase():
该方法将返回大写更改的字符值。 例如:对于“ f”输入,输出为“ F”。
charAt():
returns the charter at the given index.
charAt():
返回给定索引的宪章。
Program to capitalize each character of the sting using JavaScript
程序使用JavaScript大写字符串的每个字符
< script >
function capitalizeEachWord(str) {
var cstr = '';
str.split('').forEach(function(char) {
cstr = cstr + char.toUpperCase();
});
return cstr;
}
console.log("Hello, world!")
var x = "learning JavaScript at include help"
var y = capitalizeEachWord(x);
console.log('x = ' + x);
console.log('y = ' + y);
</script>
Output
输出量
Hello, world!
learning JavaScript at include help
LEARNING JAVASCRIPT AT INCLUDE HELP
翻译自: https://www.includehelp.com/code-snippets/capitalize-words-in-a-string-in-javascript.aspx