如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
函数 capitalizeEachWord(str) { return str.replace(/\w\S*/g,函数(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } document.write(capitalizeEachWord('foo BAR God bAD'));
其他回答
您可以使用 String#chatAt 获取第一个字符,将其转向上方,然后将其与链条的剩余部分相结合。
function capitalizeFirstLetter(v) {
return v.charAt(0).toUpperCase() + v.substring(1);
}
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
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)
function cap(input) {
return input.replace(/[\.\r\n\t\:\;\?\!]\W*(\w)/g, function(match, capture) {
// For other sentences in the text
return match.toUpperCase();
}).replace(/^\W*\w/, function(match, capture) {
// For the first sentence in the text
return match.toUpperCase();
});;
}
var a = "hi, dear user. it is a simple test. see you later!\r\nbye";
console.log(cap(a));
// Output: Hi, dear user. It is a simple test. See you later!
// Bye
只是因为你可以,这并不意味着你应该,但是. 它需要 ECMAScript 6 因为代码使用序列破坏。
const capitalizeFirstLetter = s => {
const type = typeof s;
if (type !== "string") {
throw new Error(`Expected string, instead received ${type}`);
}
const [firstChar, ...remainingChars] = s;
return [firstChar.toUpperCase(), ...remainingChars].join("");
};