Javascript split string with regex and then join it


Keywords:javascript 


Question: 

Hey I want a function that can split a string for example "(12/x+3)*heyo" which i could edit each number, letter and word by itself and then return the edited version. So far i got this (which not work as intended):

function calculate(input){
    var vars = input.split(/[+-/*()]/);
    var operations = input.split(/[^+-/*()]/);
    var output = "";

    vars = vars.map(x=>{
        return x+"1";
    });

    for(var i=0; i<operations.length; i++){
        output += operations[i]+""+((vars[i])?vars[i]:"");
    }
    return output;
}

For example: (12/x+3)*heyo returns: (1121/x1+31)*1heyo1 but should return (121/x1+31)*heyo1


3 Answers: 

You can use regex and replace method for this task:

var s = "(12/x+3)*heyo";

console.log(
  s.replace(/([a-zA-Z0-9]+)/g, "$1" + 1)
)
 

It looks like the vars array is populated with empty results, which are adding "1" inadvertently. I slightly modified your arrow function to check x for a value.

vars = vars.map(x=>{
    if (x) {
       return x+"1";
    }
});