Skip to content
Advertisement

JavaScript regex get + – * / after a number

Hey I want to make a simple calculator. The calculator should do negatives and so I want to split my input string where I match a “+ – * /”

Input is for example “5+-3” so I want to match only the “+” because the “-” is part of my second number “-3”

The regex that I have at the moment is:

/(+|-|*|)/

But this gives me the ” +” and “-“

Advertisement

Answer

You can use

/([*/]|b[-+])/

See the regex demo.

The [*/]|b[-+] pattern matches either

  • [*/] – a * or / char
  • | – or
  • b[-+] – a - or + immediately preceded with a word char.
Advertisement