简体   繁体   English

如何使用JavaScript分割字符串

[英]How can I split strings using javascript

I have these results from calling a function in javascript: 我从javascript中调用函数得到了以下结果:

(1, 00), (2, 10), (3, 01), (4, 11)

I want to assign that in an array or json format that will result like this: 我想将其分配为数组或json格式,结果如下:

[{id:1, number: 00},{id:2, number: 10},{id:3, number: 01},{id:4, number: 11}]

Or anything that will result an array lenght of 4 或任何会导致数组长度为4的东西

Is that possible? 那可能吗? Please help. 请帮忙。 Thanks :) 谢谢 :)

Use regex to get the pattern and generate the array based on the matched content. 使用正则表达式获取模式并根据匹配的内容生成数组。

 var data = '(1, 00), (2, 10), (3, 01), (4, 11)'; // regex to match the pattern var reg = /\\((\\d+),\\s?(\\d+)\\)/g, m; // array for result var res = []; // iterate over each match while (m = reg.exec(data)) { // generate and push the object res.push({ id: m[1], number: m[2] }); } console.log(res); 


Or by splitting the string. 或通过拆分字符串。

 var data = '(1, 00), (2, 10), (3, 01), (4, 11)'; var res = data // remove the last and first char .slice(1, -1) // split the string .split(/\\),\\s?\\(/) // iterate over the array to generate result .map(function(v) { // split the string var val = v.split(/,\\s?/); // generate the array element return { id: val[0], number: val[1] } }) console.log(res); 

Beside the other splitting solution, you could use String#replace and replace/add the wanted parts for a valid JSON string and use JSON.parse for parsing the string for an object, you want. 除了其他拆分解决方案之外,您还可以使用String#replace并替换/添加所需部分,以获取有效的JSON字符串,并使用JSON.parse解析所需的对象的字符串。

 var data = '(1, 00), (2, 10), (3, 01), (4, 11)', json = data.replace(/\\(/g, '{"id":').replace(/,\\s?(?=\\d)/g, ',"number":"').replace(/\\)/g, '"}'), object = JSON.parse('[' + json + ']'); console.log(object); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM