Даже если это не самый простой способ, вы можете сделать это:
var addressString = "~john smith~123 Street~Apt 4~New York~NY~12345~",
keys = "name address1 address2 city state zipcode".split(" "),
address = {};
// clean up the string with the first replace
// "abuse" the second replace to map the keys to the matches
addressString.replace(/^~|~$/g).replace(/[^~]+/g, function(match){
address[ keys.unshift() ] = match;
});
// address will contain the mapped result
address = {
address1: "123 Street"
address2: "Apt 4"
city: "New York"
name: "john smith"
state: "NY"
zipcode: "12345"
}
Обновление для ES2015 с использованием деструктуризации
const [address1, address2, city, name, state, zipcode] = addressString.match(/[^~]+/g);
// The variables defined above now contain the appropriate information:
console.log(address1, address2, city, name, state, zipcode);
// -> john smith 123 Street Apt 4 New York NY 12345