如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
这样做的一个简单的方式是:
如果您想将其添加到 String.prototype:
其他回答
使用 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(' ');
}
我最近在一个项目中需要类似的功能,这就是我如何实施它:
函数 capitlizeFirst(str) { // checks for null, undefined and empty string if (!str) return; return str.match("^[a-z]")? str.charAt(0).toUpperCase() + str.substring(1) : str; } console.log(capitlizeFirst("")); console.log(capitlizeFirst(null)); console.log(capitlizeFirst(undefined)); console.log(capitlizeFirst("hello world")); console.log(capitlizeFirst("/index.html"));
只是因为这是一个真正的单线,我会包括这个答案. 这是一个基于ES6的交叉线单线。
let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;
你可以做这样的事情:
mode = "string";
string = mode.charAt(0).toUpperCase() + mode.substr(1,mode.length).toLowerCase();
console.log(string);
这将打印
线条
你应该这样做:
let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);