有一种简单的方法可以将字符串转换为标题大小写吗?例如john smith
变为John Smith
。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)某种一线或两线。
使用JavaScript将字符串转换为标题大小写
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
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".
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)"
Try this, shortest way:
str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
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();
});
}
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(' ')
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(' ');
}
这是我的版本,IMO,也很容易理解和优雅。
var str = "foo bar baz"
console.log(
str.split(' ')
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
.join(' ')
)
// returns "Foo Bar Baz"
尝试这个:
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>
稍微更优雅的方式,可以适应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();
For those of us who are scared of regular expressions (lol):