如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/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'
其他回答
这将容忍可能领先的白空间,并不会错过一条线中的第一字母的目标,因此,它可能会改善已经在线上可用的好解决方案。
str = " the Eifel Tower";
str.replace(/\w/, str.match(/\w/)[0].toUpperCase());
>> " The Eifel Tower";
但是,如果对白条行进行执行,则会导致“软”错误,为了避免这种可能的错误或对白条行或数字进行不必要的处理,可以使用温和的条件警卫:
+str!=+str ? str.replace(/\w/, str.match(/\w/)[0].toUpperCase()) : str;
下面是更以对象为导向的方法:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
你会称之为这个功能,如下:
"hello, world!".capitalize();
预计产量是:
"Hello, world!"
var capitalizeMe = "string not starting with capital"
资本化与substr
var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);
使用步枪功能:
const capitalize = string => string[0].toUpperCase() + string.slice(1)
下面有一个函数称为ucfirst((缩写为“上例第一字母”):
function ucfirst(str) {
var firstLetter = str.substr(0, 1);
return firstLetter.toUpperCase() + str.substr(1);
}
您可以通过称 ucfirst(“某些链条”)来资本化一个链条 - 例如,
ucfirst("this is a test") --> "This is a test"
在第一行中,它提取第一Letter,然后在第二行中,它通过呼叫第一Letter.toUpperCase()来资本化第一Letter,并将其与其余的行列相结合,这是通过呼叫str.substr(1)来找到的。
你可能认为这会失败一个空的线条,而且实际上在一个语言如C,你会不得不为此加密,但是在JavaScript中,当你采取一个空的线条,你只是得到一个空的线条。