如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
看看这个解决方案:
var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master
其他回答
如果你想在一个字符串中资本化每一个字,你可以使用以下字符串:
'all_lowercase Capitalized lower_then_Upper a'.replace(/(?<=\b)[a-z](?=\w*)/g, c => c.toUpperCase())
// prints "All_lowercase Capitalized Lower_then_Upper A"
如果我可以稍微改变代码,我发现,如果我通过这个功能运行一条所有条线,什么都不会发生,所以......这里是我的条线。
String.prototype.capitalize = function(){
return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
}
一条线(“输入线可以设置到任何条线”):
inputString.replace(/.{1}/, inputString.charAt(0).toUpperCase())
在 CoffeeScript 中,添加一个字符串的原型:
String::capitalize = ->
@substr(0, 1).toUpperCase() + @substr(1)
使用将是:
"woobie".capitalize()
谁得益:
"Woobie"
String.prototype.capitalize = function(allWords) {
return (allWords) ? // If all words
this.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive
// calls until capitalizing all words
this.charAt(0).toUpperCase() + this.slice(1); // If allWords is undefined, capitalize only the first word,
// meaning the first character of the whole string
}
然后:
"capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
"capitalize all words".capitalize(true); ==> "Capitalize All Words"
更新2016年11月(ES6),只是为了乐趣:
const capitalize = (string = '') => [...string].map( // Convert to array with each item is a char of
// string by using spread operator (...)
(char, index) => index ? char : char.toUpperCase() // Index true means not equal 0, so (!index) is
// the first character which is capitalized by
// the `toUpperCase()` method
).join('') // Return back to string
此分類上一篇: 你好(Hello)