My working code:
const myString = "a=*aaa;b=*bbb";
let params = [];
myString.split(";").forEach(element => {
let zz = element.split('=');
params.push(zz[1]);
});
console.log(params.map((element, index) => index '=' element).join(';'));
CodePudding user response:
You can make params
a const
It is an array, and you are just appending items.
You can merge the two statements in the loop
You are let
ting a variable, and then just using it once.
You can convert the whole process into a .map
Instead of creating an empty array and appending things to it, you can map the array of ";" separated strings into a corresponding array of the strings you want.
Applying all 3 steps, you get this:
const myString = "a=*aaa;b=*bbb";
const params = myString.split(";").map(
element => element.split('=')[1]
);
console.log(params.map((element, index) => index '=' element).join(';'));
CodePudding user response:
I would put them in an object.
const myString = "a=*aaa;b=*bbb";
let params = {};
myString.split(";").forEach(element => {
let zz = element.split('=');
params[zz[0]] = zz[1];
});
console.log(params);