将JS中每个单词的首字母大写 [英] Capitalize first letter of each word in JS

查看:219
本文介绍了将JS中每个单词的首字母大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何将字符串中每个单词的第一个字母大写,对于这个解决方案,我理解除了word.substr(1)部分之外的所有内容。我看到它正在添加破碎的字符串但是(1)如何工作?

I'm learning how to capitalize the first letter of each word in a string and for this solution I understand everything except the word.substr(1) portion. I see that it's adding the broken string but how does the (1) work?

function toUpper(str) {
return str
    .toLowerCase()
    .split(' ')
    .map(function(word) {
        return word[0].toUpperCase() + word.substr(1);
    })
    .join(' ');
 }
 console.log(toUpper("hello friend"))


推荐答案

返回值包含2部分:

return word[0].toUpperCase() + word.substr(1);

1) word [0] .toUpperCase():这是第一个大写字母

1) word[0].toUpperCase(): It's the first capital letter

2) word.substr(1)除了首字母已被资本化。这是 substr 如何运作的文件。

2) word.substr(1) the whole remain word except the first letter which has been capitalized. This is document for how substr works.

如果你想调试,请参考下面的结果:

Refer below result if you want to debug:

function toUpper(str) {
return str
    .toLowerCase()
    .split(' ')
    .map(function(word) {
        console.log("First capital letter: "+word[0]);
        console.log("remain letters: "+ word.substr(1));
        return word[0].toUpperCase() + word.substr(1);
    })
    .join(' ');
 }
 console.log(toUpper("hello friend"))

这篇关于将JS中每个单词的首字母大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆