tengo esta cadena:
var str = "current_year:45;last_year:20;all:65";Me gustaría tener este resultado usando regex o split:
var a = ["current_year", "last_year", "all"] var b = ["45", "20", "65"] Ya intenté usar esto: /([^:\s]+):([^:\s]+)/g , pero no funcionó bien
Cualquier sugerencia ?
La mejor solución es usar split aquí. Si desea una solución de expresiones regulares, puede hacer lo siguiente:
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) Usar coincidencia, mapa y 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) Usando reemplazar solo
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; }Comenzando con current_year:45;last_year:20;all:65
Si divides en ; y luego divida cada resultado en : obtendrá:
[ [ 'current_year', '45' ], [ 'last_year', '20' ], [ 'all', '65' ] ]Luego, puede asignarlo a dos matrices separadas o a un objeto.
Como dos matrices:
[ 'current_year', 'last_year', 'all' ] [ '45', '20', '65' ]Como objeto:
{ current_year: '45', last_year: '20', all: '65' }Usando este código:
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);