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?
I wanted to add my own answer as I needed a robust
toTitleCase
function that takes into account grammar rules listed here (Google recommended article). There are various rules that depend on the length of the input string. Below is the function + unit tests.The function also consolidates whitespace and removes special characters (modify regex for your needs)
toTitleCase Function
Unit Tests to Ensure Correctness
Please note that I am removing quite a bit of special characters from the strings provided. You will need to tweak the regex to address the requirements of your project.
Try to apply the text-transform CSS style to your controls.
eg:
(text-transform: capitalize);
Only use a JS approach when absolutely necessary.
I made this function which can handle last names (so it's not title case) such as "McDonald" or "MacDonald" or "O'Toole" or "D'Orazio". It doesn't however handle German or Dutch names with "van" or "von" which are often in lower-case... I believe "de" is often lower-case too such as "Robert de Niro". These would still have to be addressed.
This is based on my solution for FreeCodeCamp's Bonfire "Title Case", which requires you to first convert the given string to all lower case and then convert every character proceeding a space to upper case.
Without using regex:
A slightly more elegant way, adapting Greg Dean's function:
Call it like:
For those of us who are scared of regular expressions (lol):