-4

I have a list of countries separated by comma like

Abnaki,Achinese,Achumawi,African,Afrikaans,Ahtena,Alabama,Albanian,Aleut,Algonquian,American Indian,American Sign Language

Now I want to convert this string in HTML format like this

<option value="Abnaki">Abnaki</option><option value="Achinese">Achinese</option><option value="Achumawi">Achumawi</option><option value="African">African</option><option value="Afrikaans">Afrikaans</option><option value="Ahtena">Ahtena</option><option value="Alabama">Alabama</option><option value="Albanian">Albanian</option><option value="Aleut">Aleut</option><option value="Algonquian">Algonquian</option><option value="American Indian" selected="selected">American Indian</option>

Is there any javascript API available to do this transformation which will also take care of special characters in the countries supplied

Cœur
  • 37,241
  • 25
  • 195
  • 267
Programmer
  • 713
  • 1
  • 8
  • 23

2 Answers2

3

You can do this using the split function and creating DOM elements manually:

var countryCsv = 'Abnaki,Achinese,Achumawi';

var countries = countryCsv.split(',');

for (var i = 0; i < countries.length; i++)
{
    var option = document.createElement('option');
    option.text = countries[i];
    option.value = countries[i];
    select.appendChild(option);
}
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
1

You didn't specify if you want a DOM tree or a string, but if you'd prefer a string my solution would be

'Abnaki,Achinese,Achumawi,African'.split(',').map(function(c) { 
  return '<option value="' + c + '">' + c + '</option>';
}).join('');

For replacing special characters (not strictly necessary depending on the encoding of your html) take a look at Encode html entities in javascript.

Community
  • 1
  • 1
mthierer
  • 594
  • 4
  • 9