
Question:
var font_name = $(".font").val();
I have this in my JavaScript code. In my html I have an input form with the class .font
.
I want to capitalize the first letter of each word in .font
, so for example if someone types in Lucida sans
it'll turn into Lucida Sans
. I couldn't find a jQuery method that does it for you so I guess I have to use actual JavaScript but I really have no idea how.
var font_first = font_name.substr(0,1);
var font = font_first.toUpperCase() + font_name.substr(1, font_name.length - 1);
I used this to capitalize the first letter of the whole font name but as I said I need to capitalize the first letter of each word.
Answer1:Can you not just use CSS?
.font {
text-transform: capitalize;
}
In jQuery:
$(".font").css("text-transform","capitalize");
Answer2:You can split on spaces, map the "uppercasing" function to each piece, and join them back together.
var font_name = $(".font").val();
font_name = font_name.split(" ")
.map(function(a) {return a.charAt(0).toUpperCase()+a.substr(1);})
.join(" ");
Alternatively, see <a href="http://phpjs.org/functions/ucwords:569" rel="nofollow">ucwords
by PHPJS</a>
In plain javascript:
<pre class="lang-js prettyprint-override">function firstcap(str) {
var len = str.length;
var re = /^\s$/;
var special = true; // signalizes whether previous char is special or not
for (var i=0; i<len; i++) {
var code = str.charCodeAt(i);
if (code>=97 && code<=122 && special) {
str = str.substr(0, i) + String.fromCharCode(code-32) + str.substr(i+1);
special = false;
}
else if (re.test(str[i])) {
special = true;
}
}
return str;
}
alert(firstcap('lucida sans'));
Answer4:
var str = "hello world";
str = str.toLowerCase().replace(/\b./g, function(letter) {
return letter.toUpperCase();
});
alert(str);
from here <a href="http://www.google.sk/url?sa=t&rct=j&q=jquery%20first%20letter%20capital&source=web&cd=1&ved=0CFUQFjAA&url=https://stackoverflow.com/questions/5122402/javascript-jquery-uppercase-first-letter-of-variable&ei=L1z3T8WANI7S4QT-_5yKBw&usg=AFQjCNEs8F1QOkyt3iO_epWLuUNa3jgzQw&cad=rja" rel="nofollow">stack</a>
Answer5:Here's a JavaScript function I just finished writing. Since I first checked StackOverflow to see if this JavaScript was around, but wasn't easily found, I'll post it for you guys to use. Hope it helps you guys, if it does, uptick me :)
var FormatMyTitle = function(UnformattedData) {
var OutgoingData = UnformattedData;
if (UnformattedData.indexOf("") != -1) {
var OptionNameParts = UnformattedData.split(' ');
for (var i=0; i<OptionNameParts.length; i++) {
var OptionNamePieces = OptionNameParts[i].split('');
if (OptionNamePieces.length >= 1) {
var FirstLetter = ''+OptionNamePieces[0]+'';
OptionNamePieces[0] = FirstLetter.toUpperCase();
}
OptionNameParts[i] = OptionNamePieces.join('');
}
OutgoingData = OptionNameParts.join(' ');
}
return OutgoingData;
};
And you would use it like so, for instance, using your original variable(font_name):
var FormattedTitle = FormatMyTitle(font_name);