使用JavaScript将字符串转换为标题大小写

JavaScript

老丝泡芙

2020-03-12

有一种简单的方法可以将字符串转换为标题大小写吗?例如john smith变为John Smith我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)某种一线或两线。

第1114篇《使用JavaScript将字符串转换为标题大小写》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

12个回答
小胖宝儿 2020.03.12

For those of us who are scared of regular expressions (lol):

function titleCase(str)
{
    var words = str.split(" ");
    for ( var i = 0; i < words.length; i++ )
    {
        var j = words[i].charAt(0).toUpperCase();
        words[i] = j + words[i].substr(1);
    }
    return words.join(" ");
}

L西门 2020.03.12
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
路易Itachi小小 2020.03.12

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".

MonsterKK梅 2020.03.12

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)"

小胖逆天 2020.03.12

Try this, shortest way:

str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
Near卡卡西小宇宙 2020.03.12
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
      return i.toUpperCase() + (r != null ? r : "");
    }
)

Seems to work... Tested with the above, "the quick-brown, fox? /jumps/ ^over^ the ¡lazy! dog..." and "C:/program files/some vendor/their 2nd application/a file1.txt".

If you want 2Nd instead of 2nd, you can change to /([a-z])(\w*)/g.

The first form can be simplified as:

function toTitleCase(toTransform) {
  return toTransform.replace(/\b([a-z])/g, function (_, initial) {
      return initial.toUpperCase();
  });
}
老丝阿飞 2020.03.12

ES 6

str.split(' ')
   .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())
   .join(' ')

else

str.split(' ').map(function (s) {
    return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
}).join(' ')
凯卡卡西 2020.03.12

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(' ');
}
宝儿Sam 2020.03.12

这是我的版本,IMO,也很容易理解和优雅。

var str = "foo bar baz"

console.log(

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

)
// returns "Foo Bar Baz"

猿GO 2020.03.12

尝试将文本转换的 CSS样式应用于控件。

例如: (text-transform: capitalize);

仅在绝对必要时才使用JS方法。

Tom老丝Pro 2020.03.12

尝试这个:

    function toTitleCase(str) {
        return str.replace(
            /\w\S*/g,
            function(txt) {
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            }
        );
    }
<form>
Input:
<br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)"  onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
<br />Output:
<br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>

Jim老丝达蒙 2020.03.12

稍微更优雅的方式,可以适应Greg Dean的功能:

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

像这样称呼它:

"pascal".toProperCase();

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android