How to make an implode to remove other characters besides the + (plus) sign with JavaScript?

0

I have this variable: 10 + 20 + 30 + 40 + 50 = 150 .

I want to know how I can use implode() of JavaScript to remove anything that is in front of each number, it can be any sign or special characters, this string can also have several sizes.

Desired result:

var numero = 10 + 20 + 30 + 40 + 50 = 150;

var 10 = 10
var 20 = 20
var 30 = 30
var 40 = 40
var 50 = 50

var igual = 150

My code:

var valor = "10+20+30+40+50=150";
var separar = valor.split('+');//Nesse caso fica limitado ao sinal de adição
alert(adicao);
    
asked by anonymous 28.10.2016 / 20:54

2 answers

4

Use a REGEX within split

  • In this case \D means that it will split when it encounters a non-numeric character.

var valor = "10+20+30+40+50=150";
var valoresSeparados = valor.split(/\D/).map(function(item) {
    return parseInt(item, 10);
});
console.log(valoresSeparados);
    
28.10.2016 / 21:24
2

Is this what you want?

var valor = "10++-20++30+40+50";
var variaveis = "";
var separar = valor.match(/(\d+)/g);

separar.forEach(function(x, indice) {
  variaveis += "var n_" + indice + " = " + x + ";\n";
});

eval(variaveis); // executando o eval para adicionar as variaveis criadas acima

var resultado = "";

separar.forEach(function(x, indice) {
  resultado += "n_" + indice + (indice == separar.length - 1 ? "" : " + ");
}); // rodando um foreach criar a linha q irá somar as variaveis

var igual = eval(resultado);

console.log("Resultado: " + igual);
    
28.10.2016 / 21:29