simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

custom_separators.html (1994B)


      1 <!DOCTYPE html>
      2 <html lang="en">
      3 <head>
      4   <meta charset="utf-8">
      5   <title>math.js | custom separators</title>
      6   <style>
      7     body, input, select {
      8       font: 11pt sans-serif;
      9     }
     10     input, select, th, #result {
     11       padding: 5px 10px;
     12     }
     13     th {
     14       text-align: left;
     15     }
     16   </style>
     17 
     18   <script src="../../lib/browser/math.js"></script>
     19 </head>
     20 <body>
     21 
     22 <p>
     23   This code example shows how to apply custom separators for function arguments and decimal separator.
     24 </p>
     25 
     26 <table>
     27   <tr>
     28     <th>Argument separator</th>
     29     <td>
     30       <input id="args" type="text" value=";">
     31     </td>
     32   </tr>
     33   <tr>
     34     <th>Decimal separator</th>
     35     <td>
     36       <input id="decimals" type="text" value=",">
     37     </td>
     38   </tr>
     39   <tr>
     40     <th>Expression</th>
     41     <td>
     42       <input id="expression" type="text" value="sum(3,4; 2,1; 2,0)" />
     43       <input id="evaluate" type="button" value="Evaluate">
     44     </td>
     45   </tr>
     46   <tr>
     47     <th>Result</th>
     48     <td id="result"></td>
     49   </tr>
     50 </table>
     51 
     52 <script>
     53   // pointers to the input elements
     54   const expression = document.getElementById('expression')
     55   const evaluate   = document.getElementById('evaluate')
     56   const result     = document.getElementById('result')
     57   const args       = document.getElementById('args')
     58   const decimals   = document.getElementById('decimals')
     59 
     60   // attach event handler to the button
     61   evaluate.onclick = function () {
     62     // replace the custom separators in the input with the default separators
     63     const expr = expression.value
     64         .replace(new RegExp('\\' + decimals.value + '|\\' + args.value, 'g'), function (match) {
     65           return match === decimals.value ? '.': ','
     66         })
     67 
     68     // do the actual evaluation
     69     const res = math.evaluate(expr)
     70 
     71     // replace the default separators in the output with custom separators
     72     result.innerHTML = res.toString()
     73         .replace(new RegExp(',|\\.', 'g'), function (match) {
     74           return match === '.' ? decimals.value : args.value
     75         })
     76   }
     77 </script>
     78 
     79 
     80 </body>
     81 </html>