0

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.

3
  • what is the goal? why not replace letters with operator and take eval? Commented Dec 7, 2022 at 18:40
  • @NinaScholz OK how would you do that? Commented Dec 7, 2022 at 18:45
  • Nevermind, I got it: eval(s.split('p').join('+').split('s').join('-')) Commented Dec 7, 2022 at 18:48

4 Answers 4

4

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 '+';
    case 's':
      return '-';
    default:
      return item;
  }
}).join('');

console.log(eval(replaced));

Sign up to request clarification or add additional context in comments.

1 Comment

Based on @NinaScholz comment, you can also use eval: eval(s.split('p').join('+').split('s').join('-'))
1

you can use match function here.

'10p6s23'.match(/[a-zA-Z]+|[0-9]+/g)

// /[a-zA-Z]+|[0-9]+/g this is the regular expression for numbers or letters

Comments

0

One way to do it is by using a Regular Expression

let s = '10p6s23'

const numbers = [...s.matchAll(/\d+/g)].map((num) => parseInt(num));
const operators = [...s.matchAll(/\D+/g)];


console.log(numbers);
console.log(operators);

And work from here with the rest of the logic

Comments

0

You could split on:

  • digits preceded by a letter i.e. (?<=[a-z])\d+ or
  • letters preceded by a digit i.e. (?<=\d)[a-z]+

Afterwards, you will have the filter on non-empty values.

const regexp = /((?<=[a-z])\d+|(?<=\d)[a-z]+)/ig;
const str = '10p6s23';

const array = str.split(regexp).filter(x => x.length);
console.log(...array);

Here is an iterative replacement solution:

const compute = (input) => {
  let
    count = input.match(/[ps]/g).length,
    result = input;
  while (count --> 0) {
    result = result.replace(
      /(\d+)([ps])(\d+)/,
      (_, left, op, right) => {
        switch (op) {
          case 'p': return parseInt(left, 10) + parseInt(right, 10);
          case 's': return parseInt(left, 10) - parseInt(right, 10);
        }
      }
    );
  }
  return result;
};

console.log(compute('10p6s23'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.