-1

I need your help,

I can't seem to be able to strip away the whitespaces in my data string before adding them to my select box.

(BTW the spaces in between the data string are deliberate as I am working with an old dataset and slowly converting it to a non-space string)

How do you accomplish this? I thought that I had the logic all right:

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">
function parseData() {

    var data = "1234567, 8910111, 9632587,6541237,9631478, 1010232"

    var options = data.split(",");

    var select = document.getElementById('list')
    select.innerHTML = ""

    for(var i=0; i<options.length; i++)
      select.options[i] = new Option(options[i], i);
}
</script>

</head>

<body>
<input type="button" value="load list" onclick="parseData()"/>
<br>
<select id="list"></select>
</body>

</html>
John Smith
  • 1,639
  • 11
  • 36
  • 51

3 Answers3

1

No Regex required, use Options[i].trim() (trim removes any whitespace (including line breaks, tab stops and whatevs) on both sites of the string)

for(var i=0; i<options.length; i++)
  select.options[i] = new Option(options[i].trim(), i);
dognose
  • 20,360
  • 9
  • 61
  • 107
  • 1
    Note that `.trim()` was added with ECMAScript 5. But, [can be polyfilled](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Compatibility) for ES3 browsers like IE8 and older. – Jonathan Lonowski Aug 14 '13 at 19:20
  • 1
    ie7 "Object doesn't support this property or method" I guess it should cross browser compatible? – John Smith Aug 14 '13 at 19:21
  • @JohnSmith IE7 does not know Trim, thats right. But IE7 is now 7 years old and has a marketshare of like 1%... Really take such an old browser into account and create work arounds? This (if you do the same for every 1% Browser) Will blow up your Javascript by like 75%... – dognose Aug 14 '13 at 19:31
1

You can trim whitespaces when filling the selector:

options[i].replace(/^\s+|\s+$/g, '')

The jsfiddle is here.

kol
  • 27,881
  • 12
  • 83
  • 120
0

Try this:

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">
function parseData() {

    var data = "1234567, 8910111, 9632587,6541237,9631478, 1010232"

    var options = data.split(",");

    var select = document.getElementById('list')
    select.innerHTML = ""

    for(var i=0; i<options.length; i++)
      select.options[i] = new Option(options[i].replace(" ", ""), i); // cross browser
      // or this one
      //select.options[i] = new Option(options[i].trim(), i); // ie9+ and all other browsers
}
</script>

</head>

<body>
<input type="button" value="load list" onclick="parseData()"/>
<br>
<select id="list"></select>
</body>

</html>
Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30