1

I have strings which are just basic math equations. How can I split each number into an array and leave the operator as its own item in the array?

"123/12*312+4-2"

The output I would like to have is the following:

["123", "/", "12", "*", "312", "+", "4", "-", "2"]

I am using this:

str.split(/[^\d]/)

All other ways of doing this keep the separator but it is part of the number instead of its own array value.

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

2 Answers2

11

Just use a capture group in regex:

var str = "123/12*312+4-2";
var arr = str.split(/(\D)/);

console.log(arr)

\D is same as [^\d] (anything but digits)

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Use String#match method.

console.log(
  "123/12*312+4-2".match(/\d+|\D/g)
)

In regex, \d+ for number combination and \D for non digit.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188