Reputation: 2297
I've got a simple list which is generated by a checkbox list. The generated code is simply this
white,blue,red,black
I need to use jquery to wrap each of these elements in a < li > tag. How do you go through the list and use the comma as a separator? I also will need to delete the comma. Sometime there will be 1 item, sometimes 3, etc.
Thanks in advance!
Upvotes: 3
Views: 3662
Reputation: 16553
<script type="text/javascript">
var mystring = 'white,blue,red,black';
mystring = '<ul><li>' + mystring.replace(/,/gi,'</li><li>') + '</li></ul>';
document.write(mystring);
</script>
Outputs:
<ul>
<li>white</li>
<li>blue</li>
<li>red</li>
<li>black</li>
</ul>
This doesn't use jquery at all :)
Upvotes: 10
Reputation: 141879
lol, 1 character shorter than omfgroflmao
:D and no jquery goodiness
mystring = '<ul>' + mystring.replace(/(\w+),?/g, '<li>$1</li>') + '</ul>';
with jquery goodiness 1 more character shortened.. haha
myobject = $('<ul>').append(mystring.replace(/(\w+),?/g, '<li>$1</li>'));
Upvotes: 1
Reputation: 8376
var el = $('#elementSelector');
var values = el.html().split(',');
el.html('<ul>' + $.map(values, function(v) {
return '<li>' + v + '</li>';
}).join('') + '</ul>');
Upvotes: 4
Reputation: 6346
var final_string = "<ul><li>" + myString.replace(/,/gi, '</li><li>') + "</li></ul>";
Upvotes: 0