如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
我需要做一个完整的名字资本化,如阿米尔·迪亚菲(Amir Diafi),所以我分裂了链条,以获得这些名字的序列,并资本化了每个字母的第一字母。
const value = 'amir diafi karim mohammed' const splited_names = value.split(' ') let capitalizedValue = '' for (const iterator of splited_names) { capitalizedValue += ` ${iterator.charAt(0).toUpperCase()}${iterator.slice(1)}` } capitalizedValue.trim() console.log(capitalizedValue) //amir diafi karim => Amir Diafi Karim
其他回答
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。
如果我可以稍微改变代码,我发现,如果我通过这个功能运行一条所有条线,什么都不会发生,所以......这里是我的条线。
String.prototype.capitalize = function(){
return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
}
这就是我宗教上所使用的:
function capitalizeMe(str, force){
str = force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/g,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
var firstName = capitalizeMe($firstName.val());
这个代码在某些情况下可能工作得很好:
函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } console.log(capitalizeFirstLetter('foo')); // Foo // 但如果我们有这样的它不会工作好 console.log(capitalizeFirstLetter('fOo')); // FOo
但是,如果你真的想确保,只有第一个字母被资本化,其余的字母是由下层字母构成的,你可以调整代码如下:
函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } console.log(capitalizeFirstLetter('fOo')); // Foo
function capitalize(s) {
// returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
return s[0].toUpperCase() + s.substr(1);
}
// examples
capitalize('this is a test');
=> 'This is a test'
capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'
capitalize('/index.html');
=> '/index.html'