简体   繁体   English

正则表达式可大写第一个字符

[英]Regex expression to capitalise first character

For the address field, I need first character of every word to be uppercase. 对于地址字段,我需要每个单词的第一个字符为大写。 I have been using /\\b./g which has eventually resulted in a problem where first character after special characters such as !@*&;' 我一直在使用/\\b./g ,这最终导致了一个问题,即特殊字符(例如!@*&;'之后的第一个字符 and so on are also capitalised. 等也要大写。 ie. 即。 King'S Street instead of King's Street . King'S Street而不是King's Street

Is there a way to adjust that expression to exclude that behaviour or is changing the entire expression more optimal? 有没有一种方法可以调整该表达式以排除该行为,或者更改整个表达式更理想?

replace \\b with (^|[ ]) \\b替换为(^|[ ])

Your regex will be: /(^|[ ])./g 您的正则表达式将是: /(^|[ ])./g

Explanation: 说明:

\\b by definition : is used to find a match at the beginning or end of a word. \\b根据定义 :用于在单词的开头或结尾查找匹配项。

(^|[ ]) will match with the beginning of the string or any space characters (^|[ ])将与字符串的开头或任何空格字符匹配

(^|[ ]). will match every space followed by a character and the first character of the string. 将匹配每个空格,后跟一个字符和字符串的第一个字符。

Side note: 边注:

Use (^|\\s) to match every blank spaces. 使用(^|\\s)匹配每个空格。

Your regex will be: /(^|\\s)./g 您的正则表达式将是:/( /(^|\\s)./g

You could use a lookahead: 您可以先行使用:

\b[a-z](?=\w+)

See a demo on regex101.com . 参见regex101.com上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM