如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
最短的 3 个解决方案, 1 和 2 处理 s 行是 “”, null 和 undefined 的情况:
s&&s[0].toUpperCase()+s.slice(1) // 32 char
s&&s.replace(/./,s[0].toUpperCase()) // 36 char - using regexp
'foo'.replace(/./,x=>x.toUpperCase()) // 31 char - direct on string, ES6
s=‘foo bar’; console.log( s&&s[0].toUpperCase()+s.slice(1) ); console.log( s&s.replace(/./,s[0].toUpperCase()); console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );
其他回答
使用此 Node.js 模块, http://stringjs.com/ 包,以资本化您的行:
var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'
下面是更以对象为导向的方法:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
你会称之为这个功能,如下:
"hello, world!".capitalize();
预计产量是:
"Hello, world!"
一个可能的解决方案:
function ConvertFirstCharacterToUpperCase(text) {
return text.substr(0, 1).toUpperCase() + text.substr(1);
}
使用此:
alert(ConvertFirstCharacterToUpperCase("this is string"));
此分類上一篇: JS Fiddle
使用 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(' ');
}
一个简单的,紧凑的功能,将完成你的工作:
const capitalize = str => str.split(' ').map(sub => sub.charAt(0).toUpperCase() + sub.slice(1)).join(' ');
“Foo” > “Foo” “Foo Bar” > “Foo Bar”