如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
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)
其他回答
解決方案 無法閱讀不定義的「charAt」財產
const capitalize = (string) => {
return string ? string.charAt(0).toUpperCase() + string.slice(1) : "";
}
console.log(capitalize("i am a programmer")); // I am a programmer
一个可能的解决方案:
function ConvertFirstCharacterToUpperCase(text) {
return text.substr(0, 1).toUpperCase() + text.substr(1);
}
使用此:
alert(ConvertFirstCharacterToUpperCase("this is string"));
此分類上一篇: JS Fiddle
yourString.replace(/\w/, c => c.toUpperCase())
我发现这支箭的功能是最容易的。 替换符合你的字符的第一个字符(\w)字符,并将其转换为顶端。
将所有单词的第一字母分为一个字符串:
function ucFirstAllWords( str )
{
var pieces = str.split(" ");
for ( var i = 0; i < pieces.length; i++ )
{
var j = pieces[i].charAt(0).toUpperCase();
pieces[i] = j + pieces[i].substr(1);
}
return pieces.join(" ");
}
函数有两个论点:
起点 - 起点指数; 长度 - 依据的长度为资本化
String.prototype.subUpper = function () {
var result = this.toString();
var start = 0;
var length = 1;
if (arguments.length > 0) {
start = arguments[0];
if (start < this.length) {
if (arguments.length > 1) {
length = arguments[1];
}
if (start + length > this.length) {
length = this.length - start;
}
var startRest = start + length;
var prefix = start > 0 ? this.substr(0, start) : String.empty;
var sub = this.substr(start, length);
var suffix = this.substr(startRest, this.length - startRest);
result = prefix + sub.toUpperCase() + suffix;
}
}
return result;
};