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:
You can try this simple code with the features of ucwords in PHP.
function ucWords(text) {
return text.split(' ').map((txt) => (txt.substring(0, 1).toUpperCase() + txt.substring(1, txt.length))).join(' ');
}
ucWords('hello WORLD');
It will keep the Upper Cases unchanged.
Html:
<input class="capitalize" name="Address" type="text" value="" />
Javascript with jQuery:
$(".capitalize").bind("keyup change", function (e) {
if ($(this).val().length == 1)
$(this).val($(this).val().toUpperCase());
$(this).val($(this).val().toLowerCase().replace(/\s[\p{L}a-z]/g, function (letter) {
return letter.toUpperCase();
}))
});
Building on @peter-olson's answer, I took a more object oriented approach without jQuery:
String.prototype.ucwords = function() {
return this.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
}
alert("hello world".ucwords()); //Displays "Hello World"
Example: http://jsfiddle.net/LzaYH/1/
I imagine you could use substring() and toUpperCase() to pull out the first character, uppercase it, and then replace the first character of your string with the result.
myString = "cheeseburger";
firstChar = myString.substring( 0, 1 ); // == "c"
firstChar.toUpperCase();
tail = myString.substring( 1 ); // == "heeseburger"
myString = firstChar + tail; // myString == "Cheeseburger"
I think that should work for you. Another thing to consider is that if this data is being displayed, you can add a class to its container that has the CSS property "text-transform: capitalize".
Based completely on @Dementric 's answer, this solution is ready to call with a simple jQuery method, 'ucwords'... Thanks to everyone who contributed here!!!
$.extend({
ucwords : function(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
}
});
EXAMPLE: This can be called using the method
var string = "this is a test";
string = $.ucwords(string); // Returns "This Is A Test"
Much easier way:
$('#test').css('textTransform', 'capitalize');
I have to give @Dementic some credit for leading me down the right path. Far simpler than whatever you guys are proposing.