Taking a list with commas and creating an unordered list

I have a simple list that is created by a list of checkboxes. Generated code is easy

white,blue,red,black

I need to use jquery to wrap each of these elements in an <li> tag. How do you view a list and use a comma as a separator? I will also need to remove the comma. Sometimes there will be 1 element, sometimes 3, etc.

Thanks in advance!

+3
source share
4 answers
<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>

It does not use jquery at all :)

+9
source
var el = $('#elementSelector');
var values = el.html().split(',');
el.html('<ul>' + $.map(values, function(v) { 
  return '<li>' + v + '</li>';
}).join('') + '</ul>');
+4
source

lol, 1 omfgroflmao: D jquery goodiness

mystring = '<ul>' + mystring.replace(/(\w+),?/g, '<li>$1</li>') + '</ul>';

jquery 1 .. -

myobject = $('<ul>').append(mystring.replace(/(\w+),?/g, '<li>$1</li>'));
+1
var final_string = "<ul><li>" + myString.replace(/,/gi, '</li><li>') + "</li></ul>";
0

Source: https://habr.com/ru/post/1740086/


All Articles