How to Capitalize the First Letter of Each Word in a String Using JavaScript

How can I capitalize the first letter of each word in a string using JavaScript?

You are not assigning your changes to the array again, so all your efforts are in vain. Try this:

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"));

How to capitalize first letter of each word, like a 2-word city?

There's a good answer here:

function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}

or in ES6:

var text = "foo bar loo zoo moo";
text = text.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');

Capitalize first letter of each word using reduce in Javascript

One option would be to treat the string as a character array, and to uppercase the character if it's either the first element in the array, or if the preceding element is a space:

const capitalize = str => [...str].reduce(  (s, c, i, a) => s + (i === 0 || a[i - 1] === ' ' ? c.toUpperCase() : c),  '');
console.log(capitalize('a short sentence'));

Javascript - Capitalizing first letter of each word in a string

You had some syntax errors, here's a corrected version of your captial_letter function:

function capital_letter (str) {
str = str.split(' ')
for (var i = 0; i < str.length; i++) {
const firstChar = str[i].charAt(0)
str[i] = firstChar.toUpperCase() + str[i].substr(1)
};

return str.join(' ')
};

The biggest one was to separate your loop parameters using ; instead of ,:

for (var i = 0; i < str.length; i++) 

p.s. looks like you might benefit from a better IDE :-)

Javascript Capitalize first letter of each word ignore Contractions

You can use

const texts = ["this_can't_be_an_example", 'this/is/an/example', 'this,is,an,example']
for (const text of texts) {
console.log(text, '=>', text.replace(/([\W_]|^)(\w)(?<!\w'\w)/g, (_, x,y) => `${x}${y.toUpperCase()}` ))
}

Javascript method to capitalize the first letter of every word and also every word after hyphen or dash

  • \d is a digit, so your expression matches a - or a digit followed by . ...
  • {1} means one occurrence, which is the default anyways...

Try something like this:

/(^\w)|([-\s]\w)/g


Related Topics



Leave a reply



Submit