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?
Thanks!
Code:
let opReg = /[\d.]/g;
let oStr = "23+5-2*-";
let oVec = oStr.split(opReg);
console.log(oVec);
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
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?
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.