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

后端 未结 17 2753
误落风尘
误落风尘 2020-11-21 05:07

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



        
17条回答
  •  孤城傲影
    2020-11-21 05:38

    Even though this is not the simplest way, you could do this:

    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"
    }
    

    Update for ES2015, using destructuring

    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
    

提交回复
热议问题