How do I split a string, breaking at a particular character?

ctrlShiftBryan picture ctrlShiftBryan · Sep 18, 2008 · Viewed 880.8k times · Source

I have this string

'john smith~123 Street~Apt 4~New York~NY~12345'

Using JavaScript, what is the fastest way to parse this into

var name = "john smith";
var street= "123 Street";
//etc...

Answer

Zach picture Zach · Sep 18, 2008

With JavaScript’s String.prototype.split function:

var input = 'john smith~123 Street~Apt 4~New York~NY~12345';

var fields = input.split('~');

var name = fields[0];
var street = fields[1];
// etc.