/**
* Title: Evaluating a string as a mathematical expression in JavaScript
* Source code in: https://www.apptic.me/blog/evaluating-mathematical-expression-javascript.php
*/
function replaceAll (haystack, needle, replace) {
return haystack.split(needle).join(replace)
} // replace all fx
const reformat = (s) => {
s = s.toLowerCase()
s = replaceAll(s, '-(', '-1*(')
s = replaceAll(s, ')(', ')*(')
s = replaceAll(s, ' ', '')
s = replaceAll(s, '-', '+-')
s = replaceAll(s, '--', '+')
s = replaceAll(s, '++', '+')
s = replaceAll(s, '(+', '(')
for (let i = 0; i < 10; i++) {
s = replaceAll(s, i + '(', i + '*' + '(')
}
while (s.charAt(0) === '+') s = s.substr(1)
// console.log(s)
return s
} // standardize string format
const strContain = (haystack, needle) => {
return haystack.indexOf(needle) > -1
} // custom true/false contains
const isParseable = (n, minus) => {
return (!isNaN(n) || (n === '-' && !minus) || n === '.')
} // determine if char should be added to side
const getSide = (haystack, middle, direction, minus) => {
let i = middle + direction
let term = ''
let limit = (direction === -1) ? 0 : haystack.length // set the stopping point, when you have gone too far
while (i * direction <= limit) { // while the current position is >= 0, or <= upper limit
if (isParseable(haystack[i], minus)) {
if (direction === 1) term = term + haystack[i]
else term = haystack[i] + term
i += direction
} else { return term }
}
return term
} // general fx to get two terms of any fx (multiply, add, etc)
const allocFx = (eq, symbol, alloc, minus) => {
minus = (typeof minus !== 'undefined') // sometimes we want to capture minus signs, sometimes not
if (strContain(eq, symbol)) {
let middleIndex = eq.indexOf(symbol)
let left = getSide(eq, middleIndex, -1, minus)
let right = getSide(eq, middleIndex, 1, false)
eq = replaceAll(eq, left + symbol + right, alloc(left, right))
}
return eq
} // fx to...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.