如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
你应该这样做:
let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);
其他回答
最短的 3 个解决方案, 1 和 2 处理 s 行是 “”, null 和 undefined 的情况:
s&&s[0].toUpperCase()+s.slice(1) // 32 char
s&&s.replace(/./,s[0].toUpperCase()) // 36 char - using regexp
'foo'.replace(/./,x=>x.toUpperCase()) // 31 char - direct on string, ES6
s=‘foo bar’; console.log( s&&s[0].toUpperCase()+s.slice(1) ); console.log( s&s.replace(/./,s[0].toUpperCase()); console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );
如果你去其中一个 regex 答案,请记住,它们只会与 ASCII 字符一起工作. 所有的 Unicode 字母都不会被打破. XRegExp 图书馆和其 Unicode 插件解决这个问题,如果你想与 regex 保持。
String.prototype.capitalize = function () {
return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}
考虑到它仍然不涵盖所有可能性(混合字符,见 http://www.regular-expressions.info/unicode.html),似乎更容易使用.charAt(0).toUpperCase() 方法。
如同它:
function capitalize(string,a) {
var tempstr = string.toLowerCase();
if (a == false || a == undefined)
return tempstr.replace(tempstr[0], tempstr[0].toUpperCase());
else {
return tempstr.split(" ").map(function (i) { return i[0].toUpperCase() + i.substring(1) }).join(" ");
}
}
capitalize('stack overflow yeah!',true)); //Stack Overflow Yeah!
capitalize('stack stack stack stack overflow yeah!'));//Stack overflow yeah!
https://jsfiddle.net/dgmLgv7b/
为了仅仅资本化第一封信,并将其余的字符串下载案例:
function capitalize(str) {
var splittedEnter = str.split(" ");
var capitalized;
var capitalizedResult;
for (var i = 0 ; i < splittedEnter.length ; i++){
capitalized = splittedEnter[i].charAt(0).toUpperCase();
splittedEnter[i] = capitalized + splittedEnter[i].substr(1).toLowerCase();
}
return splittedEnter.join(" ");
}
capitalize("tHiS wiLL be alL CapiTaLiZED.");
结果将是:
这一切都将被资本化。
发表一个编辑 @salim 的答案,包括本地字母转换。
var str = "test string";
str = str.substring(0,1).toLocaleUpperCase() + str.substring(1);