如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
总是更好地处理这些类型的东西使用CSS首先,一般来说,如果你可以用CSS解决一些事情,先去,然后尝试JavaScript解决你的问题,所以在这种情况下尝试使用CSS的第一字母,并应用文本转换:资本化;
所以,试着为此创建一个类,这样你就可以在全球范围内使用它,例如:.first-letter-uppercase 并在你的 CSS 中添加下面的类似内容:
.first-letter-uppercase:first-letter {
text-transform:capitalize;
}
另一个选项是JavaScript,所以最好的会是这样的东西:
function capitalizeTxt(txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}
把它称为:
capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html'); // return '/index.html'
capitalizeTxt('alireza'); // return 'Alireza'
capitalizeTxt('dezfoolian'); // return 'Dezfoolian'
如果你想重复使用它一次又一次,最好将其添加到JavaScript Native String,所以如下:
String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
把它称为下面的:
'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt(); // return '/index.html'
'alireza'.capitalizeTxt(); // return 'Alireza'
其他回答
解決方案 無法閱讀不定義的「charAt」財產
const capitalize = (string) => {
return string ? string.charAt(0).toUpperCase() + string.slice(1) : "";
}
console.log(capitalize("i am a programmer")); // I am a programmer
如果你需要所有的字母,从一个字母开始,你可以使用以下函数:
const capitalLetters = (s) => {
return s.trim().split(" ").map(i => i[0].toUpperCase() + i.substr(1)).reduce((ac, i) => `${ac} ${i}`);
}
例子:
console.log(`result: ${capitalLetters("this is a test")}`)
// Result: "This Is A Test"
在这里,单行代码存档字母第一字母资本使用JS
yourstring?.charAt(0)?.toUpperCase() + yourstring?.slice(1).toLocaleLowerCase()
你可以做 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)
每个链条的第一个字符都被资本化了。
函数资本化(词){返回词[0].toUpperCase() + word.slice(1).toLowerCase(); } console.log(capitalize(“john”)); //John console.log(capitalize(“BRAVO”)); //Bravo console.log(capitalize(“BLAne”)); //Blane