如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
有几种方法可以做到这一点,请尝试下面的
var lower = 'the Eiffel Tower';
var upper = lower.charAt(0).toUpperCase() + lower.substr(1);
如果你很舒服的常规表达,你会这样做:
var upper = lower.replace(/^\w/, function (chr) {
return chr.toUpperCase();
});
你甚至可以通过使用更现代化的合成来迈出一步:
const upper = lower.replace(/^\w/, c => c.toUpperCase());
此外,这也将照顾如示例中提到的负面场景,如从特殊字符开始的单词,如!@#$%^&*()}{{[];':",<>/?。
其他回答
任何类型的字符串都可以转换 -
此分類上一篇: Yourstring
var str = yOuRsTrING.toLowerCase(); // Output: yourstring
str.charAt(0).toUpperCase() + str.slice(1); // Output: Y + ourstring = Yourstring
优雅
const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;
你可以做 str.replace(str[0], str[0].toUpperCase())。
看看这个例子:
let str = “Hello, WORLD!” let newStr = str.replace(str[0], str[0].toUpperCase()) console.log(“str:”, str) console.log(“newStr:”, newStr)
下面是我所使用的功能:
capitalCase(text: string = 'NA') {
return text
.trim()
.toLowerCase()
.replace(/\w\S*/g, (w) => w.replace(/^\w/, (c) => c.toUpperCase()));
}
console.log('this cApitalize TEXt');
或者你可以使用Sugar.js资本()
例子:
'hello'.capitalize() -> 'Hello'
'hello kitty'.capitalize() -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'