问题描述
在字符串中大写单词的最佳方法是什么?
What is the best approach to capitalize words in a string?
推荐答案
在字符串中大写单词的最短实现是以下使用ES6的箭头功能:
The shortest implementation for capitalizing words within a string is the following using ES6's arrow functions:
'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'
正则表达式基本匹配给定字符串中每个单词的第一个字母并仅转换那封信为大写:
The regex basically matches the first letter of each word within the given string and transforms only that letter to uppercase:
- 匹配单词边界(单词的开头或结尾);
- 匹配以下元字符[a-zA-Z0-9]。
- \b matches a word boundary (the beginning or ending of word);
- \w matches the following meta-character [a-zA-Z0-9].
'ÿö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:
- 与空白字符匹配
- 匹配非空白字符
- 匹配任何指定的替代方案
- \s matches a whitespace character
- \S matches a non-whitespace character
- (x|y) matches any of the specified alternatives
非-capturing group可以在这里使用如下 /(?:^ | \ s)\S / g
虽然 g
我们的正则表达式中的标志无论如何都不会按设计捕获子组。
A non-capturing group could have been used here as follows /(?:^|\s)\S/g
though the g
flag within our regex wont capture sub-groups by design anyway.
干杯!
这篇关于在字符串中大写单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!