Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Split string by loop in loop

I've got string with IDs and Names separated by ^ (between ID and Names) and ; (between sets) for example

var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";

I need to get something like this

$('#1').html('<option value="1">John Smith</option><option value="2">Sophia Williams</option><option value="3">Emily Johnson</option>');

I tried loops but got stuck:

var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";

var a = string.split(";"),
    i;
for (i = 0; i < a.length; i++){
  if (a[i] !== ""){
    var b = a[i].split("^"),
    i2;
    for (var i2 = 0; i2 < b.length; i++) {
      var name = b[i2];
      console.log(name);
    }
  }
}

Im not sure that it's good way

like image 742
Bizit Avatar asked Feb 06 '26 20:02

Bizit


1 Answers

Using Option()

new Option(text, value, defaultSelected, selected)

var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;"

var options = string.split(';').map(i => {
  return new Option(...i.split('^').reverse())
})

$('#1').html(options)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<select id="1"></select>
like image 140
User863 Avatar answered Feb 09 '26 11:02

User863