Convert string to title case with JavaScript

2018-12-31 01:48发布

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.

30条回答
怪性笑人.
2楼-- · 2018-12-31 02:14

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:

function toTitleCase(str)
{
    return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}

Works for hyphenated names like Jim-Bob too.

查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 02:15

I think the simplest is using css.

function format_str(str) {
    str = str.toLowerCase();
    return '<span style="text-transform: capitalize">'+ str +'</span>';
}
查看更多
倾城一夜雪
4楼-- · 2018-12-31 02:16

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.

查看更多
谁念西风独自凉
5楼-- · 2018-12-31 02:18

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.

"SOFÍA vergara".toLowerCase().replace(/\b(\s\w|^\w)/g, function (txt) { return txt.toUpperCase(); });

The result is "Sofía Vergara".

查看更多
回忆,回不去的记忆
6楼-- · 2018-12-31 02:19

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.

function title(str) {
  return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

You can add this to your string prototype which will allow you to 'my string'.toTitle() as follows:

String.prototype.toTitle = function() {
  return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}
查看更多
时光乱了年华
7楼-- · 2018-12-31 02:19

Try this

String.prototype.toProperCase = function(){
    return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, 
        function($1){
            return $1.toUpperCase();
        }
    );
};

Example

var str = 'john smith';
str.toProperCase();
查看更多
登录 后发表回答