如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
试试这个代码:
alert("hello".substr(0, 1).toUpperCase() + "hello".substr(1));
它正在采取“你好”中的第一个字符,资本化它,并添加其余的。
其他回答
对于另一个案例,我需要它来资本化第一封信,下载其余的案例,下列案例让我改变了这个功能:
//es5
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo") // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO") // => "Alberto"
capitalize("ArMaNdO") // => "Armando"
// es6 using destructuring
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。
s[0].toUpperCase``+s.substr`1`
let s = 'hello there' console.log( s[0].toUpperCase''+s.substr`1` )
试试这个代码:
alert("hello".substr(0, 1).toUpperCase() + "hello".substr(1));
它正在采取“你好”中的第一个字符,资本化它,并添加其余的。
只是因为你可以,这并不意味着你应该,但是. 它需要 ECMAScript 6 因为代码使用序列破坏。
const capitalizeFirstLetter = s => {
const type = typeof s;
if (type !== "string") {
throw new Error(`Expected string, instead received ${type}`);
}
const [firstChar, ...remainingChars] = s;
return [firstChar.toUpperCase(), ...remainingChars].join("");
};