Javascript JS中每个单词的首字母大写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42755664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capitalize first letter of each word in JS
提问by RomeP
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?
我正在学习如何将字符串中每个单词的第一个字母大写,对于这个解决方案,我理解除了 word.substr(1) 部分之外的所有内容。我看到它正在添加断开的字符串,但是 (1) 是如何工作的?
function toUpper(str) {
return str
.toLowerCase()
.split(' ')
.map(function(word) {
return word[0].toUpperCase() + word.substr(1);
})
.join(' ');
}
console.log(toUpper("hello friend"))
回答by Ngoan Tran
The return value contain 2 parts:
返回值包含两部分:
return word[0].toUpperCase() + word.substr(1);
1) word[0].toUpperCase(): It's the first capital letter
1) word[0].toUpperCase(): 这是第一个大写字母
2) word.substr(1)the whole remain word except the first letter which has been capitalized. This is document for how substrworks.
2)word.substr(1)除了第一个大写的字母外,其余的整个单词。这是substr如何工作的文档。
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"))
回答by Pablo Palacios
Or you could save a lot of time and use Lodash
或者你可以节省大量时间并使用 Lodash
Look at
https://lodash.com/docs/4.17.4#startCase-added/edited-
https://lodash.com/docs/4.17.4#capitalize
看看
https://lodash.com/docs/4.17.4#startCase -added/edited-
https://lodash.com/docs/4.17.4#capitalize
Ex.
前任。
-added/edited-
You may what to use startCase, another function for capitalizing first letter of each word.
-添加/编辑-
您可以使用 startCase,这是另一个用于将每个单词的第一个字母大写的功能。
_.startCase('foo bar');
// => 'Foo Bar'
and capitalize for only the first letter on the sentence
并且只将句子的第一个字母大写
_.capitalize('FRED');
// => 'Fred'
Lodash is a beautiful js library made to save you a lot of time.
Lodash 是一个漂亮的 js 库,可以为您节省大量时间。
There you will find a lot of time saver functions for strings, numbers, arrays, collections, etc.
在那里你会发现很多用于字符串、数字、数组、集合等的节省时间的函数。
Also you can use it on client or server (nodejs) side, use bower or node, cdn or include it manually.
您也可以在客户端或服务器 (nodejs) 端使用它,使用 bower 或 node、cdn 或手动包含它。
回答by Mohammad Jamal Dashtaki
Here is a quick code snippet. This code snippet will allow you to capitalize the first letter of a string using JavaScript.
这是一个快速的代码片段。此代码片段将允许您使用 JavaScript 将字符串的第一个字母大写。
function CapitlizeString(word)
{
return word.charAt(0).toUpperCase() + word.slice(1);
}
回答by Roger
function titleCase(str) {
return str.toLowerCase().split(' ').map(x=>x[0].toUpperCase()+x.slice(1)).join(' ');
}
titleCase("I'm a little tea pot");
titleCase("sHoRt AnD sToUt");
回答by Gonzalo Pincheira Arancibia
The major part of the answers explains to you how works the substr(1). I give to you a better aproach to resolve your problem
答案的主要部分向您解释了 substr(1) 的工作原理。我给你一个更好的方法来解决你的问题
function capitalizeFirstLetters(str){
return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
return letter.toUpperCase();
})
}
Explanation:
- First convert the entire string to lower case
- Second check the first letter of the entire string and check the first letter that have a space character before and replaces it applying .toUpperCase()method.
说明: - 首先将整个字符串转换为小写 - 其次检查整个字符串的第一个字母并检查前面有空格字符的第一个字母并应用.toUpperCase()方法替换它。
Check this example:
检查这个例子:
function capitalizeFirstLetters(str){
return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
return letter.toUpperCase();
})
}
console.log(capitalizeFirstLetters("a lOt of words separated even much spaces "))
回答by Marvin Danig
Consider an arrow function with an implicit return:
考虑一个带有隐式返回的箭头函数:
word => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`
This will do it in one line.
这将在一行中完成。
回答by Marvin Danig
function titlecase(str){
let titlecasesentence = str.split(' ');
titlecasesentence = titlecasesentence.map((word)=>{
const firstletter = word.charAt(0).toUpperCase();
word = firstletter.concat(word.slice(1,word.length));
return word;
});
titlecasesentence = titlecasesentence.join(' ');
return titlecasesentence;
}
titlecase('this is how to capitalize the first letter of a word');
回答by Elliott Frisch
substris a function that returns (from the linked MDN) a new string containing the extracted section of the given string(starting from the secondcharacter in your function). There is a comment on the polyfillimplementation as well, which adds Get the substring of a string.
substr是一个函数,它返回(从链接的 MDN)一个包含给定字符串的提取部分的新字符串(从函数中的第二个字符开始)。也有关于polyfill实现的注释,它添加了Get 字符串的子字符串。
回答by spinkus
The regexp /\b\w/matches a word boundaryfollowed by a word character. You can use this with the replace()string method to match then replace such characters (without the g(global) regexp flag only the first matching char is replaced):
正则表达式/\b\w/匹配单词边界后跟单词字符。您可以将其与replace()string 方法一起使用来匹配然后替换这些字符(没有g(全局)regexp 标志,仅替换第一个匹配的字符):
> 'hello my name is ...'.replace(/\b\w/, (c) => c.toUpperCase());
'Hello my name is ...'
> 'hello my name is ...'.replace(/\b\w/g, (c) => c.toUpperCase());
'Hello My Name Is ...'
回答by KevBot
Here is an example of how substrworks: When you pass in a number, it takes a portion of the string based on the index you provided:
下面是一个substr工作原理示例:当您传入一个数字时,它会根据您提供的索引获取一部分字符串:
console.log('Testing string'.substr(0)); // Nothing different
console.log('Testing string'.substr(1)); // Starts from index 1 (position 2)
console.log('Testing string'.substr(2));
So, they are taking the first letter of each word, capitalizing it, and then adding on the remaining of the word. Ance since you are only capitalizing the first letter, the index to start from is always 1.
因此,他们取每个单词的第一个字母,将其大写,然后添加单词的其余部分。由于您只将第一个字母大写,因此开始的索引始终为1。

