在字符串中大写单词的最佳方法是什么?
当前回答
还有loctus: https://locutus.io/php/strings/ucwords/,它是这样定义的:
function ucwords(str) {
// discuss at: http://locutus.io/php/ucwords/
// original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// improved by: Waldo Malqui Silva (http://waldo.malqui.info)
// improved by: Robin
// improved by: Kevin van Zonneveld (http://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// bugfixed by: Cetvertacov Alexandr (https://github.com/cetver)
// input by: James (http://www.james-bell.co.uk/)
// example 1: ucwords('kevin van zonneveld')
// returns 1: 'Kevin Van Zonneveld'
// example 2: ucwords('HELLO WORLD')
// returns 2: 'HELLO WORLD'
// example 3: ucwords('у мэри был маленький ягненок и она его очень любила')
// returns 3: 'У Мэри Был Маленький Ягненок И Она Его Очень Любила'
// example 4: ucwords('τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός')
// returns 4: 'Τάχιστη Αλώπηξ Βαφής Ψημένη Γη, Δρασκελίζει Υπέρ Νωθρού Κυνός'
return (str + '').replace(/^(.)|\s+(.)/g, function ($1) {
return $1.toUpperCase();
});
};
其他回答
既然每个人都给了您所要求的JavaScript答案,我将添加CSS属性text-transform: capitalize将执行此操作。
我意识到这可能不是你想要的-你没有给我们任何上下文,你正在运行这个-但如果它只是为了表示,我肯定会选择CSS替代方案。
只要输入字符串中没有重音字母,vsync提供的答案就可以工作。
我不知道原因,但显然\b在regexp匹配也重音字母(在IE8和Chrome上测试),所以像“località”这样的字符串会被错误地大写转换为“LocalitÀ”(à字母被大写,因为regexp认为这是一个单词边界)
一个更通用的函数也适用于重音字母是这样的:
String.prototype.toCapitalize = function()
{
return this.toLowerCase().replace(/^.|\s\S/g, function(a) { return a.toUpperCase(); });
}
你可以这样使用它:
alert( "hello località".toCapitalize() );
我将使用regex来实现这个目的:
myString = ' this Is my sTring. ';
myString.trim().toLowerCase().replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));
我的解决方案:
String.prototype.toCapital = function () {
return this.toLowerCase().split(' ').map(function (i) {
if (i.length > 2) {
return i.charAt(0).toUpperCase() + i.substr(1);
}
return i;
}).join(' ');
};
例子:
'álL riGht'.toCapital();
// Returns 'Áll Right'
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
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何删除表中特定列的第一个字符?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置