如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
使用:
var str = “ruby java”; console.log(str.charAt(0).toUpperCase() + str.substring(1));
它将输出“Ruby java”到控制台。
其他回答
var nameP = prompt("please enter your name");
var nameQ = nameP.slice(0,1);
var nameR = nameP.slice(1,100);
nameQ = nameQ.toUpperCase();
nameP = nameQ + nameR;
console.log("Hello! " + nameP);
出口:
Hello! Alex
下面是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
带有箭功能
let fLCapital = s => s.replace(/./, c => c.toUpperCase())
fLCapital('this is a test') // "This is a test"
用火箭功能,另一种解决方案
let fLCapital = s => s = s.charAt(0).toUpperCase() + s.slice(1);
fLCapital('this is a test') // "This is a test"
与 Array 和 地图()
let namesCapital = names => names.map(name => name.replace(/./, c => c.toUpperCase()))
namesCapital(['james', 'robert', 'mary']) // ["James", "Robert", "Mary"]
尝试下列功能:
function capitalize (string) {
return [].map.call(string, (char, i) => i ? char : char.toUpperCase()).join('')
}
使用:
capitalize('hello, world!')
结果:
Hello, world!
使用原型
String.prototype.capitalize = function () {
return this.charAt(0) + this.slice(1).toLowerCase();
}
或使用功能
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}