function capitalize(s){return s && s[0].toUpperCase() + s.slice(1);}
es版本
const capitalize = s => s && s[0].toUpperCase() + s.slice(1)
// to always return type string event when s may be falsy other than empty-stringconst capitalize = s => (s && s[0].toUpperCase() + s.slice(1)) || ""
String.prototype.capitalize = function(allWords) {return (allWords) ? // If all wordsthis.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive// calls until capitalizing all wordsthis.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
var str = "foo bar baz";
// Capitalizestr.split(' ').map(w => w[0].toUpperCase() + w.substr(1).toLowerCase()).join(' ')// Returns "Foo Bar Baz"
// Capitalize the first letterstr.charAt(0).toUpperCase() + str.slice(1)// Returns "Foo bar baz"
function capitalizeMe(str, force){str = force ? str.toLowerCase() : str;return str.replace(/(\b)([a-zA-Z])/g,function(firstLetter){return firstLetter.toUpperCase();});}
var firstName = capitalizeMe($firstName.val());
function capitalize(s) {// returns the first letter capitalized + the string from index 1 and out aka. the rest of the stringreturn s[0].toUpperCase() + s.substr(1);}
// examplescapitalize('this is a test');=> 'This is a test'
capitalize('the Eiffel Tower');=> 'The Eiffel Tower'
capitalize('/index.html');=> '/index.html'
typeof str != "undefined" // Is str set? // truestr += '' // Turns the string variable into a stringstr[0].toUpperCase() // Get the first character and make it upper case+ // Addstr.substr(1) // String starting from the index 1 (starts at 0): // false''; // Returns an empty string
function capitalizeEachWord(str) {return str.replace(/\w\S*/g, function(txt) {return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});}
document.write(capitalizeEachWord('foo BAR God bAD'));
function cap(input) {return input.replace(/[\.\r\n\t\:\;\?\!]\W*(\w)/g, function(match, capture) {// For other sentences in the textreturn match.toUpperCase();}).replace(/^\W*\w/, function(match, capture) {// For the first sentence in the textreturn 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
'this is a test'.capitalizeTxt(); // return 'This is a test''the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower''/index.html'.capitalizeTxt(); // return '/index.html''alireza'.capitalizeTxt(); // return 'Alireza'
consistantCapitalizeFirstLetter在Internet Explorer 3+中正常工作(当const更改为var时)。prettyCapitalizeFirstLetter需要Internet Explorer 5.5+(参见本文件的第250页顶部)。然而,这些事实更多的只是笑话,因为您网页上的其余代码很可能甚至无法在Internet Explorer 8中工作-因为所有的DOM和JScript错误以及这些旧浏览器中缺乏功能。此外,没有人再使用Internet Explorer 3或Internet Explorer 5.5了。
function capitalize(str) {
const word = [];
for(let char of str.split(' ')){word.push(char[0].toUpperCase() + char.slice(1))}
return word.join(' ');
}
capitalize("this is a test");
<!DOCTYPE html><dl><dt>Untransformed<dd>ijsselmeer<dt>Capitalized with CSS and <code>lang=en</code><dd lang="en" style="text-transform: capitalize">ijsselmeer<dt>Capitalized with CSS and <code>lang=nl</code><dd lang="nl" style="text-transform: capitalize">ijsselmeer
const firstLetterToUpperCase = value => {return value.replace(value.split("")["0"], // Split stirng and get the first lettervalue.split("")["0"].toString().toUpperCase() // Split string and get the first letter to replace it with an uppercase value);};
/** As terse as possible, assuming you're using ES version 6+*/var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());
console.log(upLetter1("the quick brown fox jumped over the lazy dog."));//\\ The quick brown fox jumped over the lazy dog. //\\
// Will make will first letter of a sentence or word uppercase
function capital(word){word = word.toLowerCase()return word[0].toUpperCase() + word.substring(1);}
// Will make first letter in each words capital
function titleCase(title) {title = title.toLowerCase();const words = title.split(' ');const titleCaseWords = words.map((word) => word[0].toUpperCase() + word.substring(1));return titleCaseWords.join(' ');}
const title = titleCase('the QUICK brown fox')const caps = capital('the QUICK brown fox')
console.log(title); // The Quick Brown Foxconsole.log(caps); // The quick brown fox
/** 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"));
结果:你好世界
示例2“第一个字符小写”:
alert(uncapitalize("Hello World, today is sunny"));
function capitalizeFirstLetter(string) {return string.charAt(0).toUpperCase() + string.slice(1);}
console.log(capitalizeFirstLetter('foo')); // Foo// But if we had like this it won't work wellconsole.log(capitalizeFirstLetter('fOo')); // FOo
但是如果你真的想确保只有第一个字母大写,其余的都是小写字母,你可以这样调整代码:
function capitalizeFirstLetter(string) {return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();}
console.log(capitalizeFirstLetter('fOo')); // Foo
const capitalize = (string) => {return string ? string.charAt(0).toUpperCase() + string.slice(1) : "";}
console.log(capitalize("i am a programmer")); // I am a programmer
let str = "i want to be capitalized." // creates the string
let splittedStr = str.split(" ") // returns an arraylet array = [] // creates a array that will be used as outputlet finalStr = "" // the output stringsplittedStr.forEach(e => array.push(e[0].toUpperCase() + e.slice(1, e.length)))
finalStr = array.join(" ") // divide the array elements and join them separated by " "s
console.log(finalStr) // I Want To Be Capitalized.
如果您想将其添加到String.prototype:
String.prototype.toCapital = function() {let str = thislet splittedStr = str.split(" ") // returns an arraylet array = [] // creates a array that will be used as outputlet finalStr = "" // the output stringsplittedStr.forEach(function(e) { array.push(e[0].toUpperCase() + e.slice(1, e.length))})
finalStr = array.join(" ") // divide the array elements and join them separated by " "s
return finalStr}
console.log("added to string.prototype!".toCapital())
const capitalize = (str) => {return `${str[0].toUpperCase()}${str.slice(1)}`// return str[0].toUpperCase() + str.slice(1) // without template string}
console.log(capitalize("this is a test"));console.log(capitalize("the Eiffel Tower"));console.log(capitalize("/index.html"));
/*"this is a test" → "This is a test""the Eiffel Tower" → "The Eiffel Tower""/index.html" → "/index.html"*/
let capitalized_sentence = "hi im a indian and im studing engineering";
let ans =str.split(' ').map(elem => elem[0].toUpperCase()+ elem.slice(1)).join(' ');
output :
console.log(ans);
Hi Im Indian And Im Studing Engineering
for only first letter of string is
str = "hello im from india";
let re = new RegExp(/^[a-z]/g);
let data = str.match(re);
data= str.replace(data[0],data[0].toUpperCase())
console.log(data);
Hello im from india