如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
这里是我的版本,我认为它很容易理解和优雅。
var str = "foo bar baz";
// Capitalize
str.split(' ')
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
.join(' ')
// Returns "Foo Bar Baz"
// Capitalize the first letter
str.charAt(0).toUpperCase() + str.slice(1)
// Returns "Foo bar baz"
其他回答
函数 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'));
一个简单的,紧凑的功能,将完成你的工作:
const capitalize = str => str.split(' ').map(sub => sub.charAt(0).toUpperCase() + sub.slice(1)).join(' ');
“Foo” > “Foo” “Foo Bar” > “Foo Bar”
下面是2018 ECMAScript 6+ 解决方案:
const str = 'The Eiffel Tower'; const newStr = `${str[0].toUpperCase()}${str.slice(1)}`; console.log('Original String:', str); // the Eiffel Tower console.log('New String:', newStr); // The Eiffel Tower
資本化和無資本化第一條線。
功能包括:
/** First Character uppercase */
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/** First Character lowercase */
function uncapitalize(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
}
例1“第一个字符上方”:
alert(capitalize("hello world"));
标签:Hello World
示例2“第一字符下载案例”:
alert(uncapitalize("Hello World, today is sunny"));
此分類上一篇: Hello World, Today Is Sunny
ucfirst函数工作,如果你这样做。
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
谢谢JP的解释。