如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
下面是我所使用的功能:
capitalCase(text: string = 'NA') {
return text
.trim()
.toLowerCase()
.replace(/\w\S*/g, (w) => w.replace(/^\w/, (c) => c.toUpperCase()));
}
console.log('this cApitalize TEXt');
其他回答
首頁 〉外文書 〉文學 〉文學 〉Capitalize First Word: Shortest
text.replace(/(^.)/, m => m.toUpperCase())
每一个字:最短
text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());
如果你想确保剩下的在底部:
text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
如果你想在一个字符串中资本化每一个字,你可以使用以下字符串:
'all_lowercase Capitalized lower_then_Upper a'.replace(/(?<=\b)[a-z](?=\w*)/g, c => c.toUpperCase())
// prints "All_lowercase Capitalized Lower_then_Upper A"
关于TypeScript
capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
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
const capitalizeName = function (name) {
const names = name.split(' ');
const namesUpper = [];
for (const n of names) {
namesUpper.push(n.replace(n[0], n[0].toUpperCase()));
}
console.log(namesUpper.join(' '));
};
capitalizeName('the Eiffel Tower')