在字符串中大写单词的最佳方法是什么?
当前回答
在字符串中大写单词的最短实现是使用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标志不会按设计捕获子组。
其他回答
这应该涵盖了最基本的用例。
const capitalize = (str) => {
if (typeof str !== 'string') {
throw Error('Feed me string')
} else if (!str) {
return ''
} else {
return str
.split(' ')
.map(s => {
if (s.length == 1 ) {
return s.toUpperCase()
} else {
const firstLetter = s.split('')[0].toUpperCase()
const restOfStr = s.substr(1, s.length).toLowerCase()
return firstLetter + restOfStr
}
})
.join(' ')
}
}
capitalize('THIS IS A BOOK') // => This Is A Book
capitalize('this is a book') // => This Is A Book
capitalize('a 2nd 5 hour boOk thIs weEk') // => A 2nd 5 Hour Book This Week
编辑:改进了映射的可读性。
我将使用regex来实现这个目的:
myString = ' this Is my sTring. ';
myString.trim().toLowerCase().replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));
用这个:
String.prototype.toTitleCase = function() { 返回this.charAt(0).toUpperCase() + this.slice(1); } 让STR = 'text'; document.querySelector(#演示)。innerText = str.toTitleCase(); <div class = "app"> <p id = "demo"></p> . < / div >
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
还有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();
});
};
推荐文章
- 一元加/数字(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不同的设置