How do I split a string, breaking at a particular character?
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.
According to ECMAScript6 ES6
, the clean way is destructuring arrays:
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';
const [name, street, unit, city, state, zip] = input.split('~');
console.log(name); // john smith
console.log(street); // 123 Street
console.log(unit); // Apt 4
console.log(city); // New York
console.log(state); // NY
console.log(zip); // 12345
You may have extra items in the input string. In this case, you can use rest operator to get an array for the rest or just ignore them:
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';
const [name, street, ...others] = input.split('~');
console.log(name); // john smith
console.log(street); // 123 Street
console.log(others); // ["Apt 4", "New York", "NY", "12345"]
I supposed a read-only reference for values and used the const
declaration.
Enjoy ES6!