如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
const capitalizeName = function (name) {
const names = name.split(' ');
const namesUpper = [];
for (const n of names) {
namesUpper.push(n.replace(n[0], n[0].toUpperCase()));
}
console.log(namesUpper.join(' '));
};
capitalizeName('the Eiffel Tower')
其他回答
在 CoffeeScript 中,添加一个字符串的原型:
String::capitalize = ->
@substr(0, 1).toUpperCase() + @substr(1)
使用将是:
"woobie".capitalize()
谁得益:
"Woobie"
好吧,这里是一个更简单的方法,空间线和这一切。
首先,你應該知道,一條線是一系列字符。
这个答案应该在所有空间线上工作。
假设你的字符串在一个变量 yourString:
const yourString = "el salvacion sucks" const capitalizeString = yourString.split(" ").长度 > 0? yourString.split(" ").map((item) => 项目[0].toUpperCase() + 项目.substring(1)).join(" ") : yourString[0].toUpperCase() + yourString.substring(1) console.log(capitalizeString)
点击 Run Code Snippet 按钮查看结果
一个可能的解决方案:
function ConvertFirstCharacterToUpperCase(text) {
return text.substr(0, 1).toUpperCase() + text.substr(1);
}
使用此:
alert(ConvertFirstCharacterToUpperCase("this is string"));
此分類上一篇: JS Fiddle
尝试下列功能:
function capitalize (string) {
return [].map.call(string, (char, i) => i ? char : char.toUpperCase()).join('')
}
使用:
capitalize('hello, world!')
结果:
Hello, world!
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'