I have a mathematical expression (formula) in string
format. What I'm trying to do is to split that string and make an array of all the operators and words collectively an array. I'm doing this by passing regex
to split()
function (As I'm new with regex
I tried to create the regex
to get my desired result). With this expression I'm getting an array seperated by operators, digits and words. But, somehow I'm getting an extra blank element in the array after each element. Have a look below to get what I'm exactly talking about.
My mathematical expression (formula):
1 2-(0.67*2)/2%2=O_AnnualSalary
Regex that I'm using to split it into an array:
this.createdFormula.split(/([?= -*/%,()])/)
What I'm expecting an array should I get:
['1', ' ', '2', '-', '(', '0', '.', '6', '7', '*', '2', ')', '/', '2', '%', '2', '=', 'O_AnnualSalary']
This what I'm getting:
['', '1', '', ' ', '', '2', '', '-', '', '(', '', '0', '', '.', '', '6', '', '7', '', '*', '', '2', '', ')', '', '/', '', '2', '', '%', '', '2', '', '=', 'O_AnnualSalary']
So far what I've tried this expressions from many posts on SO:
this.createdFormula.split(/([?= -\\*\\/%,()])/)
this.createdFormula.split(/([?=\\\W -\\*\\/%,()])/)
this.createdFormula.split(/([?=//\s -\\*\\/%,()])/)
this.createdFormula.split(/([?= -\\*\\/%,()])(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)/)
this.createdFormula.split(/([?= -\\*\\/%0-9,()])/)
Can anyone help me to fix this expression to get the desired result? If you need any more information please feel free to ask.
Any help is really appreciated.
Thanks
CodePudding user response:
Assuming you have string match()
available, we can use:
var input = "1 2-(0.67*2)/2%2=O_AnnualSalary,HwTotalDays";
var parts = input.match(/(?:[0-9.,%()=/* -]|\w )/g);
console.log(parts);