简体   繁体   中英

How can I split strings using javascript

I have these results from calling a function in 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:

[{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

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.

 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; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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