Javascript 将字符串中的单词大写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2332811/
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 words in string
提问by vsync
What is the best approach to capitalize words in a string?
将字符串中的单词大写的最佳方法是什么?
回答by disfated
/**
* Capitalizes first letters of words in string.
* @param {string} str String to be modified
* @param {boolean=false} lower Whether all other letters should be lowercased
* @return {string}
* @usage
* capitalize('fix this string'); // -> 'Fix This String'
* capitalize('javaSCrIPT'); // -> 'JavaSCrIPT'
* capitalize('javaSCrIPT', true); // -> 'Javascript'
*/
const capitalize = (str, lower = false) =>
(lower ? str.toLowerCase() : str).replace(/(?:^|\s|["'([{])+\S/g, match => match.toUpperCase());
;
- fixes Marco Demaio's solution where first letter with a space preceding is not capitalized.
- 修复了Marco Demaio的解决方案,其中前面带有空格的第一个字母不是大写。
capitalize(' javascript'); // -> ' Javascript'
- can handle national symbols and accented letters.
- 可以处理国家符号和带重音的字母。
capitalize('бабушка курит трубку'); // -> 'Бабушка Курит Трубку'
capitalize('località àtilacol') // -> 'Località àtilacol'
- can handle quotes and braces.
- 可以处理引号和大括号。
capitalize(`"quotes" 'and' (braces) {braces} [braces]`); // -> "Quotes" 'And' (Braces) {Braces} [Braces]
回答by Ivo
The shortest implementation for capitalizing words within a string is the following using ES6's arrow functions:
使用 ES6 的箭头函数将字符串中的单词大写的最短实现如下:
'your string'.replace(/\b\w/g, l => l.toUpperCase())
// => 'Your String'
ES5 compatible implementation:
ES5兼容实现:
'your string'.replace(/\b\w/g, function(l){ return l.toUpperCase() })
// => 'Your String'
The regex basically matches the first letter of each word within the given string and transforms only that letter to uppercase:
正则表达式基本上匹配给定字符串中每个单词的第一个字母,并仅将该字母转换为大写:
- \bmatches a word boundary (the beginning or ending of word);
- \wmatches the following meta-character [a-zA-Z0-9].
For non-ASCII characters refer to this solution instead
对于非 ASCII 字符,请参考此解决方案
'??ur stri?g'.replace(/(^|\s)\S/g, l => l.toUpperCase())
This regex matches the first letter and every non-whitespace letter preceded by whitespace within the given string and transforms only that letter to uppercase:
此正则表达式匹配给定字符串中的第一个字母和每个以空格开头的非空格字母,并仅将该字母转换为大写:
- \smatches a whitespace character
- \Smatches a non-whitespace character
- (x|y)matches any of the specified alternatives
A non-capturing group could have been used here as follows /(?:^|\s)\S/gthough the gflag within our regex wont capture sub-groups by design anyway.
/(?:^|\s)\S/g尽管g我们的正则表达式中的标志无论如何都不会通过设计捕获子组,但可以在此处使用非捕获组,如下所示。
Cheers!
干杯!
回答by vsync
function capitalize(s){
return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );
};
capitalize('this IS THE wOrst string eVeR');
output: "This Is The Worst String Ever"
输出:“这是有史以来最糟糕的字符串”
Update:
更新:
It appears this solution supersedes mine: https://stackoverflow.com/a/7592235/104380
看来这个解决方案取代了我的:https: //stackoverflow.com/a/7592235/104380
回答by Marco Demaio
The answer provided by vsyncworks as long as you don't have accented lettersin the input string.
只要输入字符串中没有带重音的字母,vsync 提供的答案就可以工作。
I don't know the reason, but apparently the \bin regexp matches also accented letters (tested on IE8 and Chrome), so a string like "località"would be wrongly capitalized converted into "Località"(the àletter gets capitalized cause the regexp thinks it's a word boundary)
我不知道原因,但显然\bin regexp 匹配也重音字母(在 IE8 和 Chrome 上测试),所以像这样的字符串"località"会被错误地大写转换为"Località"(à字母被大写,因为正则表达式认为它是一个单词边界)
A more general function that works also with accented lettersis this one:
一个更通用的函数也适用于重音字母是这个:
String.prototype.toCapitalize = function()
{
return this.toLowerCase().replace(/^.|\s\S/g, function(a) { return a.toUpperCase(); });
}
You can use it like this:
你可以这样使用它:
alert( "hello località".toCapitalize() );
回答by Buhake Sindi
Using JavaScript and html
使用 JavaScript 和 html
String.prototype.capitalize = function() {
return this.replace(/(^|\s)([a-z])/g, function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
};
<form name="form1" method="post">
<input name="instring" type="text" value="this is the text string" size="30">
<input type="button" name="Capitalize" value="Capitalize >>" onclick="form1.outstring.value=form1.instring.value.capitalize();">
<input name="outstring" type="text" value="" size="30">
</form>
Basically, you can do string.capitalize()and it'll capitalize every 1st letter of each word.
基本上,你可以这样做string.capitalize(),它会将每个单词的每个第一个字母大写。
Source: http://www.mediacollege.com/internet/javascript/text/case-capitalize.html
来源:http: //www.mediacollege.com/internet/javascript/text/case-capitalize.html
回答by dxh
Since everyone has given you the JavaScript answer you've asked for, I'll throw in that the CSS property text-transform: capitalizewill do exactly this.
由于每个人都给了您所要求的 JavaScript 答案,我将指出 CSS 属性text-transform: capitalize将完全做到这一点。
I realize this mightnot be what you're asking for - you haven't given us any of the context in which you're running this - but if it's just for presentation, I'd definitely go with the CSS alternative.
我意识到这可能不是你所要求的——你没有给我们任何运行它的上下文——但如果它只是为了演示,我肯定会选择 CSS 替代方案。
回答by meouw
John Resig (of jQuery fame ) ported a perl script, written by John Gruber, to JavaScript. This script capitalizes in a more intelligent way, it doesn't capitalize small words like 'of' and 'and' for example.
John Resig(以 jQuery 闻名)将一个由 John Gruber 编写的 perl 脚本移植到 JavaScript。此脚本以更智能的方式大写,例如,它不会大写诸如“of”和“and”之类的小词。
You can find it here: Title Capitalization in JavaScript
你可以在这里找到它:JavaScript 中的标题大写
回答by vicke4
If you're using lodashin your JavaScript application, You can use _.capitalize:
如果您使用lodash在你的JavaScript应用程序,你可以使用_.capitalize:
console.log( _.capitalize('??ur stri?g') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
回答by Big Money
Ivo's answer is good, but I prefer to not match on \wbecause there's no need to capitalize 0-9 and A-Z. We can ignore those and only match on a-z.
Ivo 的回答很好,但我更喜欢不匹配,\w因为不需要大写 0-9 和 AZ。我们可以忽略这些,只匹配 az。
'your string'.replace(/\b[a-z]/g, match => match.toUpperCase())
// => 'Your String'
It's the same output, but I think clearer in terms of self-documenting code.
这是相同的输出,但我认为在自记录代码方面更清晰。
回答by Otman Zaib
A concise ES6 way of doing it might look something like this.
一个简洁的 ES6 方法可能看起来像这样。
const capitalizeFirstLetter = s => s.charAt(0).toUpperCase() + s.slice(1)
This only uppercases the first letterand doesn't affect the rest of the sentence's casing.
这只会将第一个字母大写,不会影响句子其余部分的大小写。

