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

162
Visualizações
Splitting a string based upon characters in javascript
<html>
<body>
    <input type="text" id="mainbox">
    <button onclick="equals()"> </button>
</body>
</html>
<script src="Calculator.js"></script>
var equation = document.getElementById('mainbox').value
function equals(){
    var equationSplit = equation.split(/\+\-/);
    console.log(equationSplit)
}

Im trying to have the array split based upon + and - signs. I'm currently in the process of just splitting it, but it always returns array length 1.

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

0

1) You should move the code of getting the value of the mainbox input value into the equals function, because you want the value after the button is pressed not after the JS is parsed.

var equation = document.getElementById('mainbox').value

2) You can use regex as /[+-]/g

enter image description here

function equals() {
  var equation = document.getElementById('mainbox').value
  var equationSplit = equation.split(/[+-]/g);
  console.log(equationSplit)
}
<input type="text" id="mainbox">
<button onclick="equals()">split</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

Your regex splits at the first sequence of '+-' which it probably doesn't find in the string.

Make the regex match either one of the characters by itself by wrapping them in [] and set the global flag to make it match multiple occurrences:

var equationSplit = equation.split(/[\+\-]/g);
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