Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda