www.webdeveloper.com
Results 1 to 5 of 5

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

  1. #1
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,437

    Question 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')+'\n\n'+tarrO.join('\n'));
    </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. #2
    Join Date
    Mar 2011
    Posts
    1,160
    Try:
    Code:
    var tarrO = strIn.match(/\d+|\+|\-|\*|\//g);

  3. #3
    Join Date
    Feb 2006
    Posts
    2,927
    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){
            tarrO= 'Bad Data!';
        }
        return tarrN+tarrO;
    }
    alert(calc('123+456-321'));

  4. #4
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    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. #5
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,437

    Thumbs up

    Quote Originally Posted by rtrethewey View Post
    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 04:25 PM. Reason: Tried secondary code suggestion

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles