如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/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() 方法。
其他回答
这是一个简单的
const upper = lower.replace(/^\w/, c => c.toUpperCase());
简单的ES6合成与模板链
const capitalize = (str) => { return `${str[0].toUpperCase()}${str.slice(1)}` // return str[0].toUpperCase() + str.slice(1) // without template string } console.log(capitalize(“这是一个测试”)); console.log(capitalize(“埃菲尔塔”)); console.log(capitalize(“/index.html”)); /* “这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/inde”
功能性方法
const capitalize = ([s, ...tring]) =>
[s.toUpperCase(), ...tring]
.join('');
然后你可以
const titleCase = str =>
str
.split(' ')
.map(capitalize)
.join(' ')
已经有这么多好答案,但你也可以使用一个简单的CSS转换:
text-transform: capitalize;
div.text-capitalize { 文本转型:资本化; } <h2>文本转型:资本化:</h2> <div class="text-capitalize">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
首頁 〉外文書 〉文學 〉文學 〉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())