如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
如果您的项目中有Lodash,请使用UpperFirst
其他回答
function capitalize(s) {
// returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
return s[0].toUpperCase() + s.substr(1);
}
// examples
capitalize('this is a test');
=> 'This is a test'
capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'
capitalize('/index.html');
=> '/index.html'
一条线(“输入线可以设置到任何条线”):
inputString.replace(/.{1}/, inputString.charAt(0).toUpperCase())
目前投票的答案是正确的,但它不会在资本化第一个字符之前切断或检查链条的长度。
String.prototype.ucfirst = function(notrim) {
s = notrim ? this : this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
return s.length > 0 ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}
设置 notrim 论点,以防止第一条线被推翻:
'pizza'.ucfirst() => 'Pizza'
' pizza'.ucfirst() => 'Pizza'
' pizza'.ucfirst(true) => ' pizza'
函数有两个论点:
起点 - 起点指数; 长度 - 依据的长度为资本化
String.prototype.subUpper = function () {
var result = this.toString();
var start = 0;
var length = 1;
if (arguments.length > 0) {
start = arguments[0];
if (start < this.length) {
if (arguments.length > 1) {
length = arguments[1];
}
if (start + length > this.length) {
length = this.length - start;
}
var startRest = start + length;
var prefix = start > 0 ? this.substr(0, start) : String.empty;
var sub = this.substr(start, length);
var suffix = this.substr(startRest, this.length - startRest);
result = prefix + sub.toUpperCase() + suffix;
}
}
return result;
};
如果您想修改全覆文本,您可能希望修改其他例子如下:
function capitalize (text) {
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}
这将确保下列文本进行更改:
TEST => Test
This Is A TeST => This is a test