Answers for "capitalize every word in a string js"

158

javascript capitalize words

//capitalize only the first letter of the string. 
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
//capitalize all words of a string. 
function capitalizeWords(string) {
    return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};
Posted by: Guest on July-22-2019
1

capitalize first letter of every word javascript

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);
Posted by: Guest on November-22-2021

Code answers related to "capitalize every word in a string js"

Code answers related to "Javascript"

Browse Popular Code Answers by Language