如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
我们将使用CSS来实现这一点,它也可以从外部CSS设置。
<span text-transform="capitalize ">The first letter of each word becomes an upper case</span>
使用Vanilla JavaScript,我们可以:
let string = "test case"
string = string[0].toUpperCase() + string.substring(1)
//return "Test case"
此分類上一篇:</b/>
字符串[0].toUpperCase():将字符串中的第一个字符转换为顶部字符串
string.substring(1):在行中删除第一个字母并返回剩余的字符
text-transform="capitalize":在这个标签的顶部字母中创建每个字母的第一个字母. 如果您使用“uppercase”作为文本转换的值,标签中的每个字母将是一个字母。
其他回答
在 CoffeeScript 中,添加一个字符串的原型:
String::capitalize = ->
@substr(0, 1).toUpperCase() + @substr(1)
使用将是:
"woobie".capitalize()
谁得益:
"Woobie"
s[0].toUpperCase``+s.substr`1`
let s = 'hello there' console.log( s[0].toUpperCase''+s.substr`1` )
使用 Tailwind CSS
<p class="capitalize">The quick brown fox</p>
此分類上一篇: Quick Brown Fox
(src: https://tailwindcss.com/docs/text-transform#transforming-text)
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。
只是因为你可以,这并不意味着你应该,但是. 它需要 ECMAScript 6 因为代码使用序列破坏。
const capitalizeFirstLetter = s => {
const type = typeof s;
if (type !== "string") {
throw new Error(`Expected string, instead received ${type}`);
}
const [firstChar, ...remainingChars] = s;
return [firstChar.toUpperCase(), ...remainingChars].join("");
};