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?
Both give the same results. They split on the numbers, but loses the operators.
var strIn = '123+456-321';
var tarrN = strIn.split(/\D/);
var tarrO = strIn.split(/\+|\-|\*|\//);
I was trying for an output of:
var tarrO = strIn.match(/\d+|\+|\-|\*|\//g);
You can replace the operators with themselves followed by a newline.
strIn= strIn.replace(/[^\.\d*\/+-]+/g, '');
var tarrN= strIn.replace(/([\D\.]+)/g, '$1\n')+ '\n\n',
tarrO= 'Bad Data!';
not the order you spec, but everything's here in this simple example (thanks to capturing parens)
you can join it yourself.
'123+456-321'.split(/([-+\/*])/) // gives == ["123", "+", "456", "-", "321"]
Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)