如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
yourString.replace(/\w/, c => c.toUpperCase())
我发现这支箭的功能是最容易的。 替换符合你的字符的第一个字符(\w)字符,并将其转换为顶端。
其他回答
如果您对每个字母的第一字母进行资本化,并且您的 usecase 在 HTML 中,您可以使用以下 CSS:
<style type="text/css">
p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>
此分類上一篇: CSS Text-Transform Property(W3Schools)
在这里,单行代码存档字母第一字母资本使用JS
yourstring?.charAt(0)?.toUpperCase() + yourstring?.slice(1).toLocaleLowerCase()
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')
在CSS中:
p::first-letter {
text-transform:capitalize;
}
我更喜欢使用一个以功能方式为导向的解决方案(例如地图序列):
Array.from(str).map((letter, i) => i === 0 ? letter.toUpperCase() : letter ).join('');