如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
如果你去其中一个 regex 答案,请记住,它们只会与 ASCII 字符一起工作. 所有的 Unicode 字母都不会被打破. XRegExp 图书馆和其 Unicode 插件解决这个问题,如果你想与 regex 保持。
String.prototype.capitalize = function () {
return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}
考虑到它仍然不涵盖所有可能性(混合字符,见 http://www.regular-expressions.info/unicode.html),似乎更容易使用.charAt(0).toUpperCase() 方法。
其他回答
下面是2018 ECMAScript 6+ 解决方案:
const str = 'The Eiffel Tower'; const newStr = `${str[0].toUpperCase()}${str.slice(1)}`; console.log('Original String:', str); // the Eiffel Tower console.log('New String:', newStr); // The Eiffel Tower
你可以做这样的事情:
mode = "string";
string = mode.charAt(0).toUpperCase() + mode.substr(1,mode.length).toLowerCase();
console.log(string);
这将打印
线条
关于TypeScript
capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
如果您使用 Underscore.js 或 Lodash, underscore.string 图书馆提供链接扩展,包括资本化:
_.capitalize(string) 将序列的第一字母转换为顶端。
例子:
_.capitalize("foo bar") == "Foo bar"
下面是我所使用的功能:
capitalCase(text: string = 'NA') {
return text
.trim()
.toLowerCase()
.replace(/\w\S*/g, (w) => w.replace(/^\w/, (c) => c.toUpperCase()));
}
console.log('this cApitalize TEXt');