search

Home  >  Q&A  >  body text

es6 - How to convert string to array in JavaScript

For example, I have a string type like this

let str="[北京,重庆,天津]"

How can I convert it to an array type?

滿天的星座滿天的星座2750 days ago1108

reply all(2)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-26 10:54:56

    If it’s standard JSON, just use JSON.parse.
    For non-standard ones, it depends on the specific situation. For your example:

    const str="[北京,重庆,天津]";
    const ans = str.slice(1, -1).split(',');

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-26 10:54:56

    Correct answer upstairs, it is very convenient to convert strings and arrays into each other in js.

    '1,2,3'.split(',') --> ['1','2','3']
    
    ['1','2','3'].join(',') ----> '1,2,3'

    reply
    0
  • Cancelreply