如何拆分字符串并将其分割为数组?

huangapple go评论58阅读模式
英文:

How to split a string and breaking it to an array?

问题

如何将字符串拆分并转换为数组?

我有一个如下所示的字符串:

1234,1243,"555,552,553"

使用JavaScript,最快的方法是如何拆分字符串并得到下面的数组:

['1234','1243','555,552,553']

英文:

How to split a string and breaking it to an array?

I have an string as shown below

1234,1243,"555,552,553"

Using JavaScript, what is the fastest way to split the string and achieve below array

['1234','1243','555,552,553']

答案1

得分: -1

需要使用正则表达式可能有更好的方法但需要多次迭代

    const str = '1234,1243,"555,552,553"';
    const regex = /"[^"]+"|[^,]+/g;
    
    const result = str.match(regex).map((item) => item.replace(/"/g, ''));

结果为 -> `array(3) ['1234', '1243', '555,552,553']`
英文:

You need to use a regex i thinks, maybe there are better way, but it's need to iterate multiple time.

const str = '1234,1243,"555,552,553"';
const regex = /"[^"]+"|[^,]+/g;

const result = str.match(regex).map((item) => item.replace(/"/g, ''));

The result is -> array(3) ['1234', '1243', '555,552,553']

huangapple
  • 本文由 发表于 2023年5月22日 23:53:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76307937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定