I have this string:
var str = "current_year:45;last_year:20;all:65";
I would like to have this result using regex or split:
var a = ["current_year", "last_year", "all"]
var b = ["45", "20", "65"]
I have already tried to use this: /([^:\s]+):([^:\s]+)/g, but it didn't work well
Any suggestion ?
The best solution is to use split here. If you want regex solution then you can do as:
var str = "current_year:45;last_year:20;all:65";
const [a, b] = str.match(/[^;]+/g).reduce(
(acc, curr) => {
const [first, second] = curr.match(/[^:]+/g);
acc[0].push(first);
acc[1].push(second);
return acc;
},
[[], []]
);
console.log(a);
console.log(b);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
2) Using match, map and forEach
var str = "current_year:45;last_year:20;all:65";
const a = [];
const b = [];
str.match(/[^;]+/g).forEach((s) => {
const [first, second] = s.match(/[^:]+/g);
a.push(first);
b.push(second);
});
console.log(a);
console.log(b);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
3) Using replace only
var str = "current_year:45;last_year:20;all:65";
const a = [];
const b = [];
str.replace(/[^;]+/g, (m) => {
const [first, second] = m.match(/[^:]+/g);
a.push(first);
b.push(second);
return "";
});
console.log(a);
console.log(b);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
Starting with
current_year:45;last_year:20;all:65
If you split on ; and then split each result on :, you'll get:
[
[ 'current_year', '45' ],
[ 'last_year', '20' ],
[ 'all', '65' ]
]
Then you can either map it to two separate arrays, or to an object.
As two arrays:
[ 'current_year', 'last_year', 'all' ]
[ '45', '20', '65' ]
As an object:
{ current_year: '45', last_year: '20', all: '65' }
Using this code:
const str = "current_year:45;last_year:20;all:65";
// Useful intermediate format
const temp = str.split(';').map(s => s.split(':'));
// As two arrays: (a) keys, and (b) values
const a = temp.map(v => v[0]);
const b = temp.map(v => v[1]);
console.log(a, b);
// Or as an object
var obj = Object.fromEntries(temp);
console.dir(obj);