Search code examples
javascriptsplit

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


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...

Solution

  • 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.