I have searched over the web can can\'t find anything to help me. I want to make the first letter of each word upper case within a variable.
So far i have tried:
just wanted to add a pure javascript solution ( no JQuery )
function capitalize(str) {
strVal = '';
str = str.split(' ');
for (var chr = 0; chr < str.length; chr++) {
strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
}
return strVal
}
console.log(capitalize('hello world'));
Easiest Way to uppercase first letter in JS
var string = "made in india";
string =string .toLowerCase().replace(/\b[a-z]/g, function(letter){return letter.toUpperCase();});
alert(string );
Result: "Made In India"
Ever heard of substr()
?
For a starter :
$("#test").text($("#test").text().substr(0,1).toUpperCase()+$("#test").text().substr(1,$("#test").text().length));
[Update:]
Thanks to @FelixKling for the tip:
$("#test").text(function(i, text) {
return text.substr(0,1).toUpperCase() + text.substr(1);
});
To do this, you don't really even need Javascript if you're going to use
$('#test').css('textTransform', 'capitalize');
Why not do this as css like
#test,h1,h2,h3 { text-transform: capitalize; }
or do it as a class and apply that class to wherever you need it
.ucwords { text-transform: capitalize; }
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"
Edit: If you are dealing with word characters other than just a-z, then the following (more complicated) regular expression might better suit your purposes.
var str = "петр данилович björn über ñaque αλφα";
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
return letter.toUpperCase();
});
alert(str); //Displays "Петр Данилович Björn Über Ñaque Αλφα"
Here is unicode-safe ucwords() function, which additionally respects double-lastnames like Russian Засс-Ранцев and some noble names like Honoré de Balzac, d'Artagnan, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd, etc:
String.prototype.ucwords = function() {
return this.toLowerCase()
.replace(/(^|\s|\-)[^\s$]/g, function(m) {
return m.toUpperCase();
})
// French, Arabic and some noble names...
.replace(/\s(Of|De|Van|Von|Ibn|Из|Ван|Фон|Ибн)\s/g, function(m) { // Honoré de Balzac, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd etc.
return m.toLowerCase();
})
.replace(/(^|\s)(D|Д)(['’][^\s$])/g, function(m, p1, p2, p3) { // D'Artagnan or d'Artagnan / Д’Артаньян или д’Артаньян
return p1 + (p1 === "" ? p2/*.toUpperCase()*/ : p2.toLowerCase()) + p3.toUpperCase();
});
}