Abk - 1 year ago 94
Javascript Question

Split a string dynamically

I have the following variables

``````var arithmetic = "96-66.33+99.3/22*58.2";
var arr;
var operator = "/*+-^";
``````

Initial question

I want to split the
`arithmetic`
at every occurrence or
`index`
of
`operator`
variable but excluding the first
`index`
of
`operator`
.

The final result will be
`["96-66.33", "+99.3", "/22", "*58.2"];`

Possible solution provided by V.Roudge

``````var arithmetic = "96-66.33+99.3/22*58.2";
arithmetic = arithmetic.split(/(?=[-+*\/])/);
console.log(arithmetic);``````

Why I don't want to split out -66.33 from 96-66.33

The
`arithmetic`
variable is an input from user, I want to grab the first expression, then continue adding up other items in the array if available.

The
`arithmetic`
variable might be only expression in the array, so splitting wouldn't be necessary.

BUT

If I can still get result to be
`["96", "-66.33", "+99.3", "/22", "*58.2"];`
I'll will appreciate. I'll just have to do some manipulation in my program.

Closest I could get you through regexp. Very close but not it exactly yet.

``````var arithmetic = "96-66.33+99.3/22*58.2";
arithmetic = arithmetic.split(/([-+*\/])/g);
console.log(arithmetic);
``````

EDIT: Got it.

``````var arithmetic = "96-66.33+99.3/22*58.2";
arithmetic = arithmetic.split(/(?=[-+*\/])/);
console.log(arithmetic);
``````

``````var arithmetic = "96-66.33+99.3/22*58.2";
arithmetic = arithmetic.split(/(?=[-+*\/])/);
console.log(arithmetic);``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download