I have a few actor names separated by commas, and I am trying to get each name in that list and plug it into a dynamically created li of its own under a ul while capitalizing the first letter only and trimming commas/spaces (the only space that should not get trimmed is between "john lock" since there is no comma there between the name) like this:
var cast = ('jack, kate ,sawyer , john lock ,, hurley')
<ul id="cast-members">
<li>Jack</li>
<li>Kate</li>
<li>Sawyer</li>
<li>John Lock</li>
<li>Hurley</li>
</ul>
Any idea how to get this accomplished with jQuery?
This should do it
var cast = 'jack, kate ,sawyer , john lock ,, hurley';
var castlist = cast.split(',');
var $ul = $('<ul>'); //create an in-memory <ul> element to hold our elements
$.each(castlist, function(idx,val){ // for each item in the split array
var value = $.trim(val).replace(/\b\S/g, function(m){return m.toUpperCase();}); // trim and capitalize the item
if (value.length > 0){ // if its length > 0 (non-empty)
var $li = $('<li>', { // create a <li> element
html: $('<a>', { // set its html to be a new <a> element
href:'Bio.html#'+value, // with a href
text:value // and a text value
})
});
$ul.append($li); // append our new <li> to the <ul>
}
});
$('.lost-cast').append( $ul ); // append the filled <ul> in the /lost-cast element
demo at http://jsfiddle.net/gaby/gvb6n/