如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
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'
其他回答
你可以做 str.replace(str[0], str[0].toUpperCase())。
看看这个例子:
let str = “Hello, WORLD!” let newStr = str.replace(str[0], str[0].toUpperCase()) console.log(“str:”, str) console.log(“newStr:”, newStr)
只是因为这是一个真正的单线,我会包括这个答案. 这是一个基于ES6的交叉线单线。
let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;
下面是更清洁、更美丽的版本。
var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());
结果:
這是一個測試 -> 這是一個測試
下面是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
尝试下列功能:
function capitalize (string) {
return [].map.call(string, (char, i) => i ? char : char.toUpperCase()).join('')
}
使用:
capitalize('hello, world!')
结果:
Hello, world!