I've got a hidden <section />
that is comprised of divs that contain content to be stuffed into a jQuery UI dialog. On document.ready I want to loop through those divs, take the id of each respective div, replace dashes with spaces, capitalize each word, and store that in a title variable. Then, I'm going use that in an object literal that gets put into my dialogs[]
array. Sounds simple, right?
Stripped down version of the HTML:
<section id="dialog-content" class="hidden">
<div id="some-dialog">
// awesome dialog content here
</div>
<div id="another-dialog">
// awesome dialog content here
</div>
<div id="modal-dialog">
// awesome dialog content here
</div>
</section>
Stripped down version of the JavaScript:
var dialogs = [],
$container = $("#dialog-content");
$content = $container.find("> div");
$content.each(function (i)
{
var $this = $(this),
id = $this.attr("id"),
title = id.replace(/\-/g, " ");
console.log(title);
dialogs[dialogs.length] =
{
trigger: $("#" + id + "-trigger"),
title: title,
content: $this.html()
};
});
BTW - I know I can use $.data()
and add custom properties to my divs, but I really wanted as minimal of markup as possible, and I am curious about this specific possibility. So it's not so much my example, but the question at hand.
To re-iterate, the question is:
How can I capitalize each word in a variable via JavaScript, just like text-transform: capitalize;
does in CSS?
You could simply write a function to do it. Here is a simple regex-based function:
function capitalize(text) {
return text.replace(/\b\w/g , function(m){ return m.toUpperCase(); } );
}