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

How to extract only minus and plus operation symbols from a string in JavaScript

I have a string let str = "+AFG21-2*AFG22+AFG23+AFG24" I want an array of operation symbols including only + and – as of above string res = ['+','-','+','+'],

For my solution, I did below but I get + only.

let str = "+AFG21-2*AFG22+AFG23+AFG24"
let rx = new RegExp(["(?<s>\\p{S}+)"].join("|"), "gmu");
let symbols = [];

for (match of str.matchAll(rx)) {
  let g = match.groups;
  switch (true) {
    case !!g.s:
      symbols.push(g.s);
      break;
  }
}

console.log(symbols);

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

>Solution :

You can just match the characters required in the square brackets

let str = "+AFG21-2*AFG22+AFG23+AFG24";
const regex = /[+-]/g

const res = str.match(regex);
console.log(res)
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