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

后端 未结 17 2397
误落风尘
误落风尘 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:19

    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!

提交回复
热议问题