Ebe Gas
Ebe Gas

Reputation: 109

Split string to array, including separator characters (parentheses, asterisk, dash) using regex

I wanted my myResult = [ '40', '-', '(', '60', '*', '2', ')' ]

let myInput = '40-(60*2)';
let myResult = myInput.split(/([*\/+-])/);
console.log(myResult)

Upvotes: 1

Views: 189

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

Include parentheses in the character set, then use .match instead of .split and alternate with numeric characters.

let myInput = '40-(60*2)';
let myResult = myInput.match(/[()*\/+-]|\d+/g);
console.log(myResult)

Upvotes: 2

Related Questions