3

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
  • 1
    You don't need the inner loop at all. Just construct the string using b[0] and b[1] where needed. Commented Mar 25, 2020 at 13:16
  • 1
    Side note: jQuery tolerates it, but #1 is an invalid selector. An ID selector cannot start with an unescaped digit. Commented Mar 25, 2020 at 13:21

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Even though it appears to work in the version of jQuery used in your answer, I'd be nervous about relying on passing an array of Options to html, it doesn't seem to be documented behavior.
@T.J.Crowder It does look very hacky to do new Option(...i.split('^').reverse()) I am not even sure how it works with the ...
@mplungjan - That part isn't a problem: It splits the string i at ^ (getting, for instance, ["1", "John Smith"]) and then reverses that array and spreads it out as two arguments to the Option constructor (text and value). :-)
Ah. Because the array works - I was not able to console.log(...i.split('^').reverse()) in a way that I could trust that new Option would like it
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.