Is there a simple way to convert a string to title case? E.g. john smith
becomes John Smith
. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Most of these answers seem to ignore the possibility of using the word boundary metacharacter (\b). A shorter version of Greg Dean's answer utilizing it:
Works for hyphenated names like Jim-Bob too.
I think the simplest is using css.
We have been having a discussion back here at the office and we think that trying to automatically correct the way people input names in the current way you want it doing is fraught with possible issues.
We have come up with several cases where different types of auto capitalization fall apart and these are just for English names alone, each language has its own complexities.
Issues with capitalizing the first letter of each name:
• Acronyms such as IBM aren’t allowed to be inputted, would turn into Ibm.
• The Name McDonald would turn into Mcdonald which is incorrect, the same thing is MacDonald too.
• Double barrelled names such as Marie-Tonks would get turned into Marie-tonks.
• Names like O’Connor would turn into O’connor.
For most of these you could write custom rules to deal with it, however, this still has issues with Acronyms as before and you get a new issue:
• Adding in a rule to fix names with Mac such as MacDonald, would the break names such as Macy turning it into MacY.
The only solution we have come up with that is never incorrect is to capitalize every letter which is a brute force method that the DBS appear to also use.
So if you want to automate the process it is as good as impossible to do without a dictionary of every single name and word and how it should be capitlized, If you don't have a rule that covers everything don't use it as it will just annoy your users and prompt people who want to enter their names correctly to go else where.
Taking the "lewax00" solution I created this simple solution that force to "w" starting with space or "w" that initiate de word, but is not able to remove the extra intermediate spaces.
The result is "Sofía Vergara".
I prefer the following over the other answers. It matches only the first letter of each word and capitalises it. Simpler code, easier to read and less bytes. It preserves existing capital letters to prevent distorting acronyms. However you can always call
toLowerCase()
on your string first.You can add this to your string prototype which will allow you to
'my string'.toTitle()
as follows:Try this
Example