Home > front end >  How to not split decimal point in math equation string using Regex in Javascript
How to not split decimal point in math equation string using Regex in Javascript

Time:01-20

I have this string that contain Math equation. And I want to split it based on the operator between number. Because later I want to use it with eval() to do math operation.

Like this:

var myString = "25 15-10/555"
var newString = myString.split(/([x -/])/).filter(Boolean);

Which I have successfully split the string like I want:

output: ["25", " ", "15", "-", "10", "/", "555"]

The problem is If I have decimal point in my string. It will separate a number that actually a decimal point number:

var myString = "2.5 15-55.50"
var newString = myString.split(/([x -/])/).filter(Boolean);

output: ["2", ".", "5", " ", "15", "-", "55", ".", "50"]

As you can see, it separate 2.5 and 55.50. How can I achieve this output: ["2.5", " ", "15", "-", "55.50"] ?

What should I do to my Regex? Or maybe there's something wrong with it?

CodePudding user response:

You almost had the correct regex, problem with /([x -/])/ is that the minus sign is interpreted as a range specifier in the character class, in this case indicating from plus ( ) to slash (/). What you could do is either escape the minus sign with a backslash:

/([x \-/])/

Or move it to the end of the character class:

/([x /-])/

CodePudding user response:

It's because - in your characters list acts as range operator and has meaning all characters between from " " till "/" (similar to [a-z].

Move it to end of list or escape:

var myString = "2.5 15-55.50"

console.log(myString.split(/([x \-/])/));

  •  Tags:  
  • Related