tags:

views:

373

answers:

3

I have strings like X,Y. I want to separate X from Y using javascript. Please describe how to as I am new at javascript

+4  A: 

Sounds like you want split(). You would use it like this:

a = "X,Y"
b = a.split(",")

This would create an array of the strings "X" and "Y" and put that in b.

unwind
A: 

Try:

var Test= "X,Y";
var Part = Test.slice(0, 1);

or

var Test = "X,Y";
var Part = Test.substr(0, 1);
Peter
this will only work if X and Y will always be one charachter...
Jan Hancic
He didn't ask to split it always on the position where the "," is, he asked how to get a substring.
Peter
+1  A: 

You could use the split() method on a string, which will split the string into a array:

var myString = "X,Y";
var myArray = myString.split ( "," );

myArray will then contain "X" on index 0, and Y on index 1

Or you could use the substring method as so:

var myString = "X,Y";
var myX = myString.substring ( 0, myString.indexOf ( "," ) );
var myY = myString.substring ( myString.indexOf ( "," ) + 1 );
Jan Hancic