如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
var nameP = prompt("please enter your name");
var nameQ = nameP.slice(0,1);
var nameR = nameP.slice(1,100);
nameQ = nameQ.toUpperCase();
nameP = nameQ + nameR;
console.log("Hello! " + nameP);
出口:
Hello! Alex
其他回答
最短的 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()) );
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(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("");
};
如果您想修改全覆文本,您可能希望修改其他例子如下:
function capitalize (text) {
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}
这将确保下列文本进行更改:
TEST => Test
This Is A TeST => This is a test
一条线路:
此分類上一篇: 重定向,重定向,重定向,重定向,重定向