Separate integers from a string and divide the integres by a constant. (JS)

Viewed 40

I have a string

let str = 'a12b-a24b';

And I'm replacing the alphabets and splitting the string into two parts

let [result1, result2] = str.replace(/a/g,'').replace(/b/g,'').split('-');

I want to divide the numbers by a constant say 2 before assigning them to result1 and result2 respectively.

1 Answers

You can shorten the replace using a character class [ab]

Then split on a hyphen and map the value to an int if they are whole numbers and divide by 2.

let str = 'a12b-a24b';
let [result1, result2] = str.replace(/[ab]/g, '')
  .split('-')
  .map(s => parseInt(s, 10) / 2);
console.log(result1)
console.log(result2);

Related