如何在字符串开头和点(.)符号之后将每个单词大写?
我对google和stackoverflow进行了研究,下面是我实现的代码,但这只会将字符串的开头大写。示例如下;
var str = 'this is a text. hello world!';
str = str.replace(/^(.)/g, str[0].toUpperCase());
document.write(str);Run Code Online (Sandbox Code Playgroud)
我想要的字符串是This is a text. Hello world!.
我尝试使用CSS,text-transform: capitalize;但这会导致每个单词都大写。
我使用这样的函数,它带有一个可选的第二个参数,该参数最初会将整个字符串转换为小写。原因是有时你有一系列的Title Case Items. That You Wish要变成一系列的Title case items. That you wish有作为句子大小写。
function sentenceCase(input, lowercaseBefore) {\n input = ( input === undefined || input === null ) ? \'\' : input;\n if (lowercaseBefore) { input = input.toLowerCase(); }\n return input.toString().replace( /(^|\\. *)([a-z])/g, function(match, separator, char) {\n return separator + char.toUpperCase();\n });\n}\nRun Code Online (Sandbox Code Playgroud)\n\n正则表达式的工作原理如下
\n\n1st Capturing Group (^|\\. *)\n 1st Alternative ^\n ^ asserts position at start of the string\n 2nd Alternative \\. *\n \\. matches the character `.` literally (case sensitive)\n * matches the character ` ` literally (case sensitive)\n * Quantifier \xe2\x80\x94 Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)\n2nd Capturing Group ([a-z])\n Match a single character present in the list below [a-z]\n a-z a single character in the range between a (ASCII 97) and z (ASCII 122) (case sensitive)\nRun Code Online (Sandbox Code Playgroud)\n\n您可以在示例中实现它,如下所示:
\n\nvar str = \'this is a text. hello world!\';\nstr = sentenceCase(str);\ndocument.write(str); // This is a text. Hello world!\nRun Code Online (Sandbox Code Playgroud)\n\n示例jsfiddle
\n\n附言。将来,我发现regex101 是一个非常有用的工具,用于理解和测试 regex
\n| 归档时间: |
|
| 查看次数: |
6610 次 |
| 最近记录: |