Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
eval() confusing two minuses `--` with decrement operator

Let me just start by saying I know using eval() is considered bad practice, but I'm using it on an application that's purely client-based, so no DBs and backends. I'm using it just for evaluating mathematical expressions.

Say I have this string which has been stripped from spaces from the beginning: "1-(2-3)". If you call eval() with it you get eval("1-(2-3)") == 1-(-1) == 2.

But here's the catch. For some complex reasons (which are irrelevant to this question), I have to evaluate the parenthesis first and replace the parenthesis with its evaluated value. So I will get the string "1--1". But if I call eval like this: eval("1--1"), it will interpret -- as an decrement operation and I get the error

Uncaught SyntaxError: Invalid left-hand side expression in postfix operation

For example,

const input = "1-(2-3)"
const str = input.replace("(2-3)", eval("(2-3)"))
console.log(str) // "1--1"
const result = eval(str) // Here things go wrong. Eval parses `--` as the decrement operator.
console.log(result)

I know this isn't a fault of eval, it's meant to evaluate general code, not just mathematical expressions, but how can I get around this?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

another option is you can just wrap eval in let str = input.replace("(2-3)", eval("(2-3)")) with parenthesis to make it let str = input.replace("(2-3)", "(${eval("(2-3)")})"). That would be the quickest workaround fort this particular problem. But different ones may arise. As Sharjeel mentioned, BODMAS is important, but another hint is: You can look into Reverse Polish Notation as this way of taking down complex equations is the way computers think basically. It will help you understand how to properly calculate longer expressions and will make your mechanism ready for different problems you may face with current version

about 4 years ago · Juan Pablo Isaza Relatório

0

Actually, I thought about it and the simplest solution is probably just using String.prototype.replaceAll() to replace all occurrences of -- to - -.

const input = "1-(2-3)"
let str = input.replace("(2-3)", eval("(2-3)"))
console.log(str) // "1--1"
str = str.replaceAll('--', '- -')
const result = eval(str)
console.log(result) // 2

about 4 years ago · Juan Pablo Isaza Relatório

0

You could pad with space for every nested expression before you add the value to the outer string.

x = '-1';
r = eval('1-' + ` ${x} `);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda