如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
s[0].toUpperCase``+s.substr`1`
let s = 'hello there' console.log( s[0].toUpperCase''+s.substr`1` )
其他回答
函数有两个论点:
起点 - 起点指数; 长度 - 依据的长度为资本化
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;
};
// Uppercase first letter
function ucfirst(field) {
field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}
使用:
<input type="text" onKeyup="ucfirst(this)" />
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)
在 CoffeeScript 中,添加一个字符串的原型:
String::capitalize = ->
@substr(0, 1).toUpperCase() + @substr(1)
使用将是:
"woobie".capitalize()
谁得益:
"Woobie"
对于另一个案例,我需要它来资本化第一封信,下载其余的案例,下列案例让我改变了这个功能:
//es5
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo") // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO") // => "Alberto"
capitalize("ArMaNdO") // => "Armando"
// es6 using destructuring
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();