如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
我一直在试图做同样的事情(即;资本化第一字母在一个字符串,而它是打字)使用jQuery. 我搜索所有通过网页的答案,但我找不到它. 但是我能够得到一个工作周围使用on()函数在jQuery如下:
$("#FirstNameField").on("keydown",function(e){
var str = $("#FirstNameField").val();
if(str.substring()===str.substring(0,1)){
$("#FirstNameField").val(str.substring(0,1).toUpperCase());
}
});
这个功能实际上资本化了第一个字母,而数据输入者则不断打字。
其他回答
已经有这么多好答案,但你也可以使用一个简单的CSS转换:
text-transform: capitalize;
div.text-capitalize { 文本转型:资本化; } <h2>文本转型:资本化:</h2> <div class="text-capitalize">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
我最近在一个项目中需要类似的功能,这就是我如何实施它:
函数 capitlizeFirst(str) { // checks for null, undefined and empty string if (!str) return; return str.match("^[a-z]")? str.charAt(0).toUpperCase() + str.substring(1) : str; } console.log(capitlizeFirst("")); console.log(capitlizeFirst(null)); console.log(capitlizeFirst(undefined)); console.log(capitlizeFirst("hello world")); console.log(capitlizeFirst("/index.html"));
将所有单词的第一字母分为一个字符串:
function capitalize(str) {
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.toLowerCase().slice(1)).join(' ');
}
创建一行资本的第一字母
第一個解決方案
“这是一个测试” → “这是一个测试”
var word = "this is a test"
word[0].toUpperCase();
他说:“这是一个测试。
第二個解決方案 第一個字的條件資本
“这是一个测试” → “这是一个测试”
function capitalize(str) {
const word = [];
for(let char of str.split(' ')){
word.push(char[0].toUpperCase() + char.slice(1))
}
return word.join(' ');
}
capitalize("this is a test");
他说:“这是一个测试。
优雅
const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;