如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
有一个非常简单的方式来实现它通过替代。
'foo'.replace(/^./, str => str.toUpperCase())
结果:
'Foo'
其他回答
最简单的解决方案是:
let yourSentence = 'it needs first letter upper case';
yourSentence.charAt(0).toUpperCase() + yourSentence.substr(1);
或:
yourSentence.charAt(0).toUpperCase() + yourSentence.slice(1);
或:
yourSentence.substr(0, 1).toUpperCase() + yourSentence.substr(1);
我更喜欢使用一个以功能方式为导向的解决方案(例如地图序列):
Array.from(str).map((letter, i) => i === 0 ? letter.toUpperCase() : letter ).join('');
資本化和無資本化第一條線。
功能包括:
/** First Character uppercase */
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/** First Character lowercase */
function uncapitalize(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
}
例1“第一个字符上方”:
alert(capitalize("hello world"));
标签:Hello World
示例2“第一字符下载案例”:
alert(uncapitalize("Hello World, today is sunny"));
此分類上一篇: Hello World, Today Is Sunny
您可以使用 String#chatAt 获取第一个字符,将其转向上方,然后将其与链条的剩余部分相结合。
function capitalizeFirstLetter(v) {
return v.charAt(0).toUpperCase() + v.substring(1);
}
带有箭功能
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"]