如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
使用步枪功能:
const capitalize = string => string[0].toUpperCase() + string.slice(1)
其他回答
我最近在一个项目中需要类似的功能,这就是我如何实施它:
函数 capitlizeFirst(str) { // checks for null, undefined and empty string if (!str) return; return str.match("^[a-z]")? str.charAt(0).toUpperCase() + str.substring(1) : str; } console.log(capitlizeFirst("")); console.log(capitlizeFirst(null)); console.log(capitlizeFirst(undefined)); console.log(capitlizeFirst("hello world")); console.log(capitlizeFirst("/index.html"));
String.prototype.capitalize = function(){
return this.replace(/(^|\s)([a-z])/g,
function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
};
使用:
capitalizedString = someString.capitalize();
此分類上一篇: This Is a Text String
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。
使用此 Node.js 模块, http://stringjs.com/ 包,以资本化您的行:
var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'
只有CSS
如果转换仅需要在网页上显示:
p::first-letter {
text-transform: uppercase;
}
尽管被称为“::第一字”,但它适用于第一个字符,即在 %a 字符的情况下,这个选择器将适用于 % 并且作为这样一个不会被资本化。
ES2015 单线
const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);
注意事项
在我所执行的指标中,在 string.charAt(0) 和 string(0) 之间没有显著的差异。 但是,请注意,该 string(0) 会为一个空的 string 不定义,因此该函数必须重写以使用“string && string(0)”,这与替代品相比是过于垂直的。
与 substring() 和 slice() 之间的比较
差异在今天相当微小(自己进行测试):
21,580,613.15 ops/s ±1.6% for substring(), 21,096,394.34 ops/s ±1.8% (2.24% 缓慢) for slice()。
此分類上一篇