在字符串中大写单词的最佳方法是什么?
当前回答
John Resig (jQuery的成名者)将John Gruber编写的perl脚本移植到JavaScript。这个脚本以一种更聪明的方式大写,它没有大写像“of”和“and”这样的小词。
你可以在这里找到它:Title资本化JavaScript
其他回答
既然每个人都给了您所要求的JavaScript答案,我将添加CSS属性text-transform: capitalize将执行此操作。
我意识到这可能不是你想要的-你没有给我们任何上下文,你正在运行这个-但如果它只是为了表示,我肯定会选择CSS替代方案。
如果你在你的JavaScript应用程序中使用lodash,你可以使用_.capitalize:
控制台日志(_。查理兹(你的字符串); <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js " > < / >
使用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 capitalizeAll(str){
var partes = str.split(' ');
var nuevoStr = "";
for(i=0; i<partes.length; i++){
nuevoStr += " "+partes[i].toLowerCase().replace(/\b\w/g, l => l.toUpperCase()).trim();
}
return nuevoStr;
}
我将使用regex来实现这个目的:
myString = ' this Is my sTring. ';
myString.trim().toLowerCase().replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));