英文:
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']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论