javascriptarraysstringsplicearray-splice

Split a array javascript using regular expressions


I am trying to split this array in 2 or 3 parts and stuck. This is what I have so far, if I use one of the splice lines it works but if I use all to test cases then does not. I want to:

  1. grab everything before the operator and combine it into one number - variable
  2. grab everything after the operator and combine it into one number - variable
  3. grab the operator and give it a separate variable
const re = /^(\+\/\-\*)$/

let store1 = ["7", "1", "+", "9", "6"]
store2 = store1.splice(0, store1.indexOf(re));

// This does not work all at once, only if one line is uncommented
//store2 = store1.splice(0, store1.indexOf('+'));
//store2 = store1.splice(0, store1.indexOf('-'));
//store2 = store1.splice(0, store1.indexOf('*'));
//store2 = store1.splice(0, store1.indexOf('/'));

console.log(store1)
console.log(store2)

I tried what I posted in the code, I have tried turning the array.toStrings() and looping through but cant make sense of it yet.


Solution

  • Given the format of the "array" looks like a string, it might be easier to parse this as a string using a slightly altered regex.

    To convert an array to a string without separators, use .join("")

    const re = /(\+|\-|\*)/;
    let store1 = ["7", "1", "+", "9", "6"];
    
    console.log(store1.join("").split(re))
    

    As needed, you can then use destructuring assignments (SO answer) to convert the array to distinct variables (assuming you only have a simple num op num):

    let [ v1, op, v2 ] = [...store1.join("").split(re)]
    

    Snippet:

    const re = /(\+|\-|\*)/;
    let store1 = ["7", "1", "+", "9", "6"];
    
    let [ v1, op, v2 ] = store1.join("").split(re);
    
    console.log(v1, op, v2);