Thread: Split equation and retain numbers and operators. Possible?

1. Split equation and retain numbers and operators. Possible?

Is there a regular expression that will split a string between operands like +, -, * or /
similar to the following attempt that only partially works?

Code:
<script type="text/javascript">
var strIn = '123+456-321';
var tarrN = strIn.split(/\D/);
var tarrO = strIn.split(/\+|\-|\*|\//);
</script>
Both give the same results. They split on the numbers, but loses the operators.
I was trying for an output of:
Code:
123
456
321

+
-

2. Registered User
Join Date
Mar 2011
Posts
1,252
Try:
Code:
var tarrO = strIn.match(/\d+|\+|\-|\*|\//g);

3. Registered User+
Join Date
Feb 2006
Posts
2,930
You can replace the operators with themselves followed by a newline.

Code:
function calc(strIn){
strIn= strIn.replace(/[^\.\d*\/+-]+/g, '');
var tarrN= strIn.replace(/([\D\.]+)/g, '\$1\n')+ '\n\n',
tarrO;
try{
tarrO= eval(strIn);
}
catch(er){
}
return tarrN+tarrO;
}

4. not the order you spec, but everything's here in this simple example (thanks to capturing parens)

Code:
'123+456-321'.split(/([-+\/*])/) // gives == ["123", "+", "456", "-", "321"]
you can join it yourself.

5. Originally Posted by rtrethewey
Try:
Code:
var tarrO = strIn.match(/\d+|\+|\-|\*|\//g);
Thank you. This is closer to what I was trying for.
'mrhoo's solution uses the eval(), which in the final analysis of my feeble attempts, was what I was trying to avoid.

Thank you both. I'll report back later with progress status.

EDIT: Just noticed mrhoo's second post. I'll give that a try as well. Thanks again!

Tried mrhoo's solution and it works just a well for my initial needs.
Last edited by JMRKER; 03-14-2013 at 03:25 PM. Reason: Tried secondary code suggestion