Blank characters produced when splitting a string


I have been trying to split my string, oStr = “23+5-2*-”, so that the vector produced contains only the mathematical operators. When I try to split the string, though, as you can see in the image, there are empty strings in the first two indices of the vector. I would like it to return [’+’, ‘-’, ‘*-’]. At first I thought that the numbers became the blanks, but I have 4 number and only 2 blanks. Does anyone have any suggestions on how to fix this?



let opReg = /[\d.]/g;

let oStr = "23+5-2*-";
let oVec = oStr.split(opReg);


you are splitting on each number, try with one or more numbers instead (+)

1 Like

It’s a matter of how split() works. If your string has nothing before/between the split pattern, then it will add an empty string to the array.
For example

var someStr = ",,a,b,,c";
someStr.split(","); // ["", "", "a", "b", "", "c"]
1 Like

I changed my regex expression to let opReg = /[\d.]+/g;, but it still has one blank at the beginning. I tried moving the plus sign around, but I wasn’t able to get rid of the last blank. Is there a way to keep it from adding the blank completely, or is there a method that doesn’t add an empty string if there’s nothing before the split pattern?

You can just remove the empty items from the array. Or you could remove values from the string before splitting it.

1 Like

If you know in advance what all the operators are, then you could do something like:

const oStr = "23+5-2*-";
const operators = oStr.match(/[-+*/]+/g);
console.log(operators); // [ '+', '-', '*-' ]

or simply look all cases of 1 or more non-digit characters. This would assume the only other character groups beside digits and decimal points are operators.

const operators = oStr.match(/[^\d.]+/g);