Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split string by all non-numeric characters

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading