如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
你可以做这样的事情:
mode = "string";
string = mode.charAt(0).toUpperCase() + mode.substr(1,mode.length).toLowerCase();
console.log(string);
这将打印
线条
其他回答
在CSS中:
p::first-letter {
text-transform:capitalize;
}
資本化和無資本化第一條線。
功能包括:
/** First Character uppercase */
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/** First Character lowercase */
function uncapitalize(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
}
例1“第一个字符上方”:
alert(capitalize("hello world"));
标签:Hello World
示例2“第一字符下载案例”:
alert(uncapitalize("Hello World, today is sunny"));
此分類上一篇: Hello World, Today Is Sunny
我最近在一个项目中需要类似的功能,这就是我如何实施它:
函数 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"));
/*
* As terse as possible, assuming you're using ES version 6+
*/
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());
console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\
如果你想在一个字符串中资本化每一个字,你可以使用以下字符串:
'all_lowercase Capitalized lower_then_Upper a'.replace(/(?<=\b)[a-z](?=\w*)/g, c => c.toUpperCase())
// prints "All_lowercase Capitalized Lower_then_Upper A"