I have a string like this:
let s = '10p6s23'
I’d like to split it in such a way that I get the numbers and the letters in an array, so ideally I’d get this:
[10,'p',6,'s',23]
The ultimate goal is to build a add/subtract calculator where p = + and s = -. So the string above would resolve to 10 + 6 - 23 = -7.
What I’ve tried
Split string into array on first non-numeric character in javascript
This worked well, except it only split on the first char, not all chars.
>Solution :
const regexp = /(\d+|[a-z]+)/g;
const str = '10p6s23';
const array = [...str.match(regexp)];
console.log(...array);
let replaced = array.map(item => {
switch(item) {
case 'p':
return '-';
break;
case 's':
return '+'
break;
default:
return item
}
}).join('');
console.log(eval(replaced));