xxxxxxxxxx
function capitalizeWords(string) {
return string.split(' ').map(word =>
word.charAt(0).toUpperCase() + word.slice(1)
).join(' ')
}
// Example usage
const sentence = 'capitalize each word in this sentence'
console.log(capitalizeWords(sentence)); // Output: Capitalize Each Word In This Sentence
xxxxxxxxxx
text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());
// Explanation:
//
// ^\w : first character of the string
// | : or
// \s\w : first character after whitespace
// (^\w|\s\w) Capture the pattern.
// g Flag: Match all occurrences.
// Example usage:
// Create a reusable function:
const toTitleCase = str => str.replace(/(^\w|\s\w)/g, m => m.toUpperCase());
// Call the function:
const myStringInTitleCase = toTitleCase(myString);
xxxxxxxxxx
const lower = 'this is an entirely lowercase string';
const upper = lower.charAt(0).toUpperCase() + lower.substring(1);
Capitalize the first letter of every word:
xxxxxxxxxx
let capitalizeFirstLetter = function (sentence) {
let wordArray = sentence.toLowerCase().split(" ");
let newSentence = [];
for (let word of wordArray) {
let capWord = word[0].toUpperCase() + word.substring(1);
newSentence.push(capWord);
}
return newSentence.join(" ");
}
xxxxxxxxxx
const string = "tHIS STRING'S CAPITALISATION WILL BE FIXED."
const string = string.charAt(0).toUpperCase() + string.slice(1)
xxxxxxxxxx
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
// You do not need to check if i is larger than splitStr length, as your for does that for you
// Assign it back to the array
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
// Directly return the joined string
return splitStr.join(' ');
}
document.write(titleCase("I'm a little tea pot"));
xxxxxxxxxx
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
xxxxxxxxxx
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
xxxxxxxxxx
// this will only capitalize the first word
var name = prompt("What is your name");
firstLetterUpper = name.slice(0,1).toUpperCase();
alert("Hello " + firstLetterUpper + name.slice(1, name.length).toLowerCase());
xxxxxxxxxx
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
console.log(capitalizeFirstLetter('foo')); // Foo
Run code snippet
xxxxxxxxxx
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.toLocaleLowerCase().substring(1)
}
capitalize("bob");