Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need to extract text after = for each value seperated by semicolon in javascript. I have done it but wondering if there is a better approach

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(';'));

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(';'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading