如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
创建一行资本的第一字母
第一個解決方案
“这是一个测试” → “这是一个测试”
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");
他说:“这是一个测试。
其他回答
这个代码在某些情况下可能工作得很好:
函数 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
如果你想在一行中资本化每个第一封信,例如Hello to the world,你可以使用以下(由史蒂夫·哈里森重复):
function capitalizeEveryFirstLetter(string) {
var splitStr = string.split(' ')
var fullStr = '';
$.each(splitStr,function(index){
var currentSplit = splitStr[index].charAt(0).toUpperCase() + splitStr[index].slice(1);
fullStr += currentSplit + " "
});
return fullStr;
}
您可以通过使用以下方式呼叫:
capitalizeFirstLetter("hello to the world");
函数 capitalizeEachWord(str) { return str.replace(/\w\S*/g,函数(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } document.write(capitalizeEachWord('foo BAR God bAD'));
使用 RamdaJs 的另一种方式,是功能编程方式:
firstCapital(str){
const fn = p => R.toUpper(R.head(p)) + R.tail(p);
return fn(str);
}
用多个字在一个字符串:
firstCapitalAllWords(str){
const fn = p => R.toUpper(R.head(p)) + R.tail(p);
return R.map(fn,R.split(' ', str)).join(' ');
}
使用:
var str = “ruby java”; console.log(str.charAt(0).toUpperCase() + str.substring(1));
它将输出“Ruby java”到控制台。