Home > front end >  I need to extract text after = for each value seperated by semicolon in javascript. I have done it b
I need to extract text after = for each value seperated by semicolon in javascript. I have done it b

Time:02-17

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 letting 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);
  • Related