-2

I have a string that always contains 8 variable values that are separated with a hypen (-) like in the following example:

5-2-2-2-2-2-2-1

What is the best way to split this into 8 separate values so that I can use each of them in a variable if the values can be either an integer or the value 'n/a' ?

Many thanks for any help with this, Tim.

user2571510
  • 11,167
  • 39
  • 92
  • 138

2 Answers2

2
 var str = '5-2-2-2-2-2-2-1';
 var parts = str.split('-');
 for (var i=0;i<parts.length;i++){
    console.log(parts[i]);
  }
andrew
  • 9,313
  • 7
  • 30
  • 61
  • Thanks for this ! I am pretty new to JS so sorry if this is a simple question but how do I get the values assigned to variables in this case ? Will the for loop just create variables with i as their name, like var1, var2 etc. ? I would need my variables be called ms1, ms2 etc. – user2571510 Mar 29 '14 at 15:10
  • 1
    `parts[0]` contains `5`, `parts[1]` contains `2`, `parts[2]` contains `2` etc. `str.split()` will produce an array. so `parts` is an array. read more about javascript arrays – andrew Mar 29 '14 at 15:13
1

You are searching for the String.split() method

achedeuzot
  • 4,164
  • 4
  • 41
  • 56