How to Make the First Letter of a String Uppercase in 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"));

Uppercase first letter of variable

Use the .replace[MDN] function to replace the lowercase letters that begin a word with the capital letter.

var str = "hello world";

str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {

return letter.toUpperCase();

});

alert(str); //Displays "Hello World"

How do I lowercase any string and then capitalize only the first letter of the word with JavaScript?

A small sample:

function firstLetter(s) {

return s.replace(/^.{1}/g, s[0].toUpperCase());
}

firstLetter('hello'); // Hello

How do I capitalize the first letter of each word in an array of strings? Writing a `for ... of ... loop ` (ES6)

You can simply loop over the days and get the first character to uppercase like this:

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

for (const day of days) {

console.log(day[0].toUpperCase() + day.substr(1));

}

capitalize first letter of string and first letter after dot

The first letter and all the first letters after the dot will be uppercase.

void main() {
String text = 'hello. i am Gabriele. i am 21 years old!';
String capitalized = capitalizeAfterDot(text);

print(capitalized); // Hello. I am Gabriele. I am 21 years old!
}

String capitalizeAfterDot(String text) {
final split = text.replaceAll(RegExp(r'\.\s+'), ' #').split(' ');
String result = split.reduce((a, b) {
if (b.startsWith('#')) {
return a + b.replaceRange(0, 2, '. ' + b[1].toUpperCase());
}
return a + ' ' + b;
});

return result.replaceRange(0, 1, result[0].toUpperCase());
}

OR

String capitalizeAll(String text) {
return text.replaceAllMapped(RegExp(r'\.\s+[a-z]|^[a-z]'), (m) {
final String match = m[0] ?? '';
return match.toUpperCase();
});
}


Related Topics



Leave a reply



Submit