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:27

If regex used in the above solutions is getting you confused, try this code:

function titleCase(str) {
  return str.split(' ').map(function(val){ 
    return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();
  }).join(' ');
}
查看更多
骚的不知所云
3楼-- · 2018-12-31 02:27

Try this, shortest way:

str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
查看更多
笑指拈花
4楼-- · 2018-12-31 02:27

Use /\S+/g to support diacritics:

function toTitleCase(str) {
  return str.replace(/\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());
}

console.log(toTitleCase("a city named örebro")); // A City Named Örebro

However: "sunshine (yellow)" ⇒ "Sunshine (yellow)"

查看更多
不流泪的眼
5楼-- · 2018-12-31 02:29

Here's my version, IMO it's easy to understand and elegant too.

var str = "foo bar baz"

str.split(' ')
   .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
   .join(' ')

// returns "Foo Bar Baz"
查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 02:32

If you can use third party libraries in your code then lodash has a helper function for us.

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'

查看更多
妖精总统
7楼-- · 2018-12-31 02:35

Just in case you are worried about those filler words, you can always just tell the function what not to capitalize.

/**
 * @param String str The text to be converted to titleCase.
 * @param Array glue the words to leave in lowercase. 
 */
var titleCase = function(str, glue){
    glue = (glue) ? glue : ['of', 'for', 'and'];
    return str.replace(/(\w)(\w*)/g, function(_, i, r){
        var j = i.toUpperCase() + (r != null ? r : "");
        return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();
    });
};

Hope this helps you out.

查看更多
登录 后发表回答