Javascript: Split string by loop in loop

Viewed 664

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

2 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>

You can build a HTML string inside your loop by grabbing the first element from b as the value for your option and the second element from b to be the text in your option tag. You can then add a string HTML version of the option tag using these text and value components to the accumulated string each iteration of your for-loop:

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

var a = string.split(";");
var html_str = "";
for (var i = 0; i < a.length-1; i++) { // loop to a.length-1 so you don't need an if-statement to check blanks
  var b = a[i].split("^");
  var val = b[0];
  var txt = b[1];
  html_str += '<option value="' + val +'">' + txt +'</option>';
}

$('#one').html(html_str);
console.log(html_str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="one"></select>

An alternative approach could be to use a regular expression to get the components from your string an convert it to your desired HTML string by using .replace() with a replacement function:

var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";
var html_str = string.replace(/(\d+)\^([^;]+);/g, (_, val, txt) => `<option value="${val}">${txt}</option>`);

$('#one').html(html_str);
console.log(html_str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="one">
</select>

The above regular expression:

  • (\d+)\^: Groups any digits (group 1) which have a carat ^ following them
  • ([^;]+);: Groups any characters which are not a semi-colon ; (group 2), which are followed by a semi-colon.

These groups are formed for each occurrence in your string, and then used in the .replace() method's callback, where group 1 is val and group 2 is txt.

Related