-1

I have the condition

var a = '2008, 1993';

I want to parse this string into

var b = 2008
var c = 1993

using javascript.

isherwood
  • 58,414
  • 16
  • 114
  • 157
user2624315
  • 327
  • 3
  • 8

3 Answers3

4
var a = '2008, 1993';
var array = a.split(',');
var b = parseInt(array[0]);
var c = parseInt(array[1]);

http://jsfiddle.net/isherwood/X57KE/

isherwood
  • 58,414
  • 16
  • 114
  • 157
1

You are looking for split function like this:

var array = '2008, 1993'.split(',');
var b = parseInt(array[0]);
var c = parseInt(array[1]);

or like this:

var a = '2008, 1993'.split(', '), b = a.shift(), c=a.shift()
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

The .split() method lets you split up a string into an array of substrings based on a separator that you specify.

var a = "2008, 2009",
    items = a.split(/, ?/),
    b = +items[0],
    c = +items[1];

I would suggest a regex /, ?/ to split on, i.e., a comma followed by an optional space - though if you know there will always be both a comma and a space you could say a.split(", ").

Since you seem to want the individual items as numbers rather than strings I have shown how to convert them using the unary plus operator.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241