如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
在CSS中:
p::first-letter {
text-transform:capitalize;
}
其他回答
这里是我的版本,我认为它很容易理解和优雅。
var str = "foo bar baz";
// Capitalize
str.split(' ')
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
.join(' ')
// Returns "Foo Bar Baz"
// Capitalize the first letter
str.charAt(0).toUpperCase() + str.slice(1)
// Returns "Foo bar baz"
首先,我只是想清楚资本化在这个背景下意味着什么,“这条线是资本化”可靠的来源
你可以从例子中看到,只要这不是OP正在寻找的东西,它应该说的是“我如何制作一条线的第一字”(不资本化线)
function ucfirst (str) {
return typeof str != "undefined" ? (str += '', str[0].toUpperCase() + str.substr(1)) : '';
}
解释
typeof str != "undefined" // Is str set
? // true
str += '' // Turns the string variable into a string
str[0].toUpperCase() // Get the first character and make it upper case
+ // Add
str.substr(1) // String starting from the index 1 (starts at 0)
: // false
''; // Returns an empty string
这将与任何论点或没有论点工作。
undefined === ""
"" === ""
"my string" === "My string"
null === "Null"
undefined === "";
false === "False"
0 === "0"
true === "True"
[] === ""
[true,0,"",false] === "True,0,,false"
为了仅仅资本化第一封信,并将其余的字符串下载案例:
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.");
结果将是:
这一切都将被资本化。
ucfirst函数工作,如果你这样做。
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
谢谢JP的解释。
下面是更以对象为导向的方法:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
你会称之为这个功能,如下:
"hello, world!".capitalize();
预计产量是:
"Hello, world!"