/    Sign up×
Community /Pin to ProfileBookmark

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(/+|-|*|//);
alert(tarrN.join(‘n’)+’nn’+tarrO.join(‘n’));
</script>

[/code]

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

+

[/code]

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@rtretheweyMar 14.2013 — Try:
<i>
</i>var tarrO = strIn.match(/d+|+|-|*|//g);
Copy linkTweet thisAlerts:
@mrhooMar 14.2013 — 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, '$1n')+ 'nn',
tarrO;
try{
tarrO= eval(strIn);
}
catch(er){
tarrO= 'Bad Data!';
}
return tarrN+tarrO;
}[/CODE]

alert(calc('123+456-321'));
Copy linkTweet thisAlerts:
@rnd_meMar 14.2013 — 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"]
[/CODE]


you can join it yourself.
Copy linkTweet thisAlerts:
@JMRKERauthorMar 14.2013 — Try:
<i>
</i>var tarrO = strIn.match(/d+|+|-|*|//g);
[/QUOTE]


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.
×

Success!

Help @JMRKER spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...