在字符串中大写单词的最佳方法是什么?
当前回答
我将使用regex来实现这个目的:
myString = ' this Is my sTring. ';
myString.trim().toLowerCase().replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));
其他回答
在字符串中大写单词的最短实现是使用ES6的箭头函数:
'your string'.replace(/\b\w/g, l => l.toUpperCase())
// => 'Your String'
ES5兼容实现:
'your string'.replace(/\b\w/g, function(l){ return l.toUpperCase() })
// => 'Your String'
regex基本上匹配给定字符串中每个单词的首字母,并只将该字母转换为大写字母:
\b匹配单词边界(单词的开头或结尾); \w匹配下面的元字符[a-zA-Z0-9]。
对于非ascii字符,请参考此解决方案
'ÿöur striñg'.replace(/(^|\s)\S/g, l => l.toUpperCase())
这个正则表达式匹配给定字符串中的第一个字母和前面有空格的每个非空格字母,并只将该字母转换为大写字母:
\s匹配一个空白字符 \S匹配非空格字符 (x|y)匹配任何指定的替代项
这里可以使用非捕获组,如下所示/(?:^|\s)\ s /g,尽管正则表达式中的g标志不会按设计捕获子组。
既然每个人都给了您所要求的JavaScript答案,我将添加CSS属性text-transform: capitalize将执行此操作。
我意识到这可能不是你想要的-你没有给我们任何上下文,你正在运行这个-但如果它只是为了表示,我肯定会选择CSS替代方案。
Ivo的答案很好,但我更喜欢不匹配\w,因为没有必要大写0-9和A-Z。我们可以忽略这些,只匹配a-z。
'your string'.replace(/\b[a-z]/g, match => match.toUpperCase())
// => 'Your String'
这是相同的输出,但我认为在自文档代码方面更清楚。
使用JavaScript和html
String.prototype.capitalize = function() { 返回this.replace (/ (^ | \ s) ([a - z]) / g函数(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"> > < /形式
基本上,你可以用string。capitalize()它会大写每个单词的第一个字母。
来源:http://www.mediacollege.com/internet/javascript/text/case-capitalize.html
function capitalize(s){
return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );
};
capitalize('this IS THE wOrst string eVeR');
输出:“这是有史以来最糟糕的字符串”
更新:
这个解决方案似乎取代了我的:https://stackoverflow.com/a/7592235/104380