Skip to content

Mustafa Ateş UZUN Blog

mustafauzun.co

  • About
  • Blog
  • Home
  • »
  • JavaScript
  • »
  • Javascript, turn function to string based calculator
  • »
    • September 16, 2022September 17, 2022
    • by mustafauzun
  • C#, JavaScript

Javascript, turn function to string based calculator

Like C#, also in javascript, it’s pretty easy to do string-based math.

By following the steps below, performing math operations or creating a simple calculator with the function class and regex can be done quickly.

(Source: My Github)

function calc(operation) {

    if(!operation.match(/[0-9%^*\/()\-+.]/g)) {
        throw 'only use numbers and operators'
    }

    //remove all whitespaces
    operation = operation.replace(/\s+/g, '')

    //if parenthesis on the side of the digit then replace
    //etc. 1(2+2) to 1*(2+2)
    operation = operation.replace(/(-?\d)(\()/g, '$1*$2')

    //etc. (2+2)1 to (2+2)*1
    operation = operation.replace(/(-?\))(\d)/g, '$1*$2')

    //etc. --+ to +
    operation = operation.replace(/\-{2}/g, '+')

    //etc. ++ more operation letter to one +
    operation = operation.replace(/\+{2,}/, '+')
    
    return Function(`return +${operation}`)()

}
Tags: c#, calculator, eval, javascript, regex
Share

C#, how to open an .exe in WinForm

Node.js, how to see javascript machine codes

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Javascript, Task Queue
  • Javascript, Thread Pool
  • Javascript, Lexical Environment
  • Javascript, Execution Context
  • Javascript, Event Delegation

Recent Comments

No comments to show.

Archives

  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • January 2022

Categories

  • C#
  • CMD
  • CSS
  • HTML
  • JavaScript
  • MongoDB
  • Node.js
  • Podcast
  • Powershell
  • Uncategorized
Theme: Puskar by Template Sell.