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

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

小胖宝儿2020/03/12 16:14:14

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 16:14:14
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
路易Itachi小小2020/03/12 16:14:14

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 16:14:14

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 16:14:14

Try this, shortest way:

str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
Near卡卡西小宇宙2020/03/12 16:14:14
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 16:14:14

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 16:14:14

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(' ');
}
宝儿Sam2020/03/12 16:14:13

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

var str = "foo bar baz"

console.log(

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

)
// returns "Foo Bar Baz"

猿GO2020/03/12 16:14:13

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

例如: (text-transform: capitalize);

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

Tom老丝Pro2020/03/12 16:14:13

尝试这个:

    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 16:14:13

稍微更优雅的方式,可以适应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();