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
  • 30,739
  • 34
  • 150
  • 294

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
  • 713,503
  • 59
  • 514
  • 593
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
  • 110,383
  • 23
  • 155
  • 178