是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
我用正则表达式回答。
更多regex信息:https://regex101.com/r/AgRM3p/1
function toTitleCase(string = '') { const regex = /^[a-z]{0,1}|\s\w/gi; string = string.toLowerCase(); string.match(regex).forEach((char) => { string = string.replace(char, char.toUpperCase()); }); return string; } const input = document.getElementById('fullname'); const button = document.getElementById('button'); const result = document.getElementById('result'); button.addEventListener('click', () => { result.innerText = toTitleCase(input.value); }); <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test</title> </head> <body> <input type="text" id="fullname"> <button id="button">click me</button> <p id="result">Result here</p> <script src="./index.js"></script> </body> </html>
其他回答
String.prototype.capitalize = function() {
return this.toLowerCase().split(' ').map(capFirst).join(' ');
function capFirst(str) {
return str.length === 0 ? str : str[0].toUpperCase() + str.substr(1);
}
}
用法:
"hello world".capitalize()
与其他答案相比,我更喜欢下面的答案。它只匹配每个单词的第一个字母,并将其大写。更简单的代码,更容易阅读和更少的字节。它保留了现有的大写字母,以防止扭曲的首字母缩写。然而,你总是可以首先在你的字符串上调用toLowerCase()。
function title(str) {
return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}
你可以把这个添加到你的字符串原型,这将允许你'my string'.toTitle()如下所示:
String.prototype.toTitle = function() {
return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}
例子: String.prototype.toTitle = function() { return this.replace(/(^|\s)\ s /g, function(t) {return t. touppercase ()}); } console.log('全部小写->','全部小写'.toTitle()); console.log('所有大写字母->','所有大写字母'.toTitle()); console.log("I'm a little teapot ->","I'm a little teapot".toTitle());
不使用正则表达式,仅供参考:
String.prototype.toProperCase = function() { Var =这个。分割(' '); Var结果= []; For (var I = 0;I < words.length;我+ +){ var letter = words[i].charAt(0).toUpperCase(); 结果。Push(字母+单词[i].slice(1)); } 返回的结果。加入(' '); }; console.log ( “约翰·史密斯”.toProperCase () )
这是我的答案,如果你的问题解决了,请评论并点赞。
function toTitleCase(str) str归来。replace ( / (\ w * w * | w *) \ s * / g, 功能(. txt) { 三年级,四年级,三年级,四年级,三年级,三年级 的 ); 的 < form > 输入: <br /><textarea" > < / textarea > < br / >输出: <br /><textarea" > < / textarea > < / form >
我做了这个函数,它可以处理姓氏(所以它不是标题大小写),如“McDonald”或“MacDonald”或“O'Toole”或“D'Orazio”。然而,它不能处理带有“van”或“von”的德语或荷兰语名称,这些名称通常是小写的。我相信“de”也经常是小写的,比如“Robert de Niro”。这些问题仍需解决。
function toProperCase(s)
{
return s.toLowerCase().replace( /\b((m)(a?c))?(\w)/g,
function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });
}