Q: Match Multiplication - JavaScript task

+2 votes

You are given a text with numbers multiplied by * in format {num1} * {num2}. Your job is to extract each two numbers in the above format, multiply them and replace them with their product.

  • The first number is integer, can be negative.
  • The second number is integer or floating-point and can be negative.

There could be whitespace around the “*” symbol.

The input comes as a single string argument – the text holding the numbers.


My bill: 2*2.50 (beer); 2* 1.20 (kepab); -2  * 0.5 (deposit).

My bill: 5 (beer); 2.4 (kepab); -1 (deposit).

The output should be printed on the console – it consists of the same text with the multiplied numbers replaced by their product.

asked in JavaScript category by user icabe

1 Answer

+2 votes

Here is the code:

function matchMultiplication(inputStr) {
    inputStr = inputStr.replace(/(-?\d+)\s*\*\s*(-?\d+(\.\d+)?)/g,
        (match, num1, num2)=> Number(num1) * Number(num2));

matchMultiplication("My bill: 2*2.50 (beer); 2* 1.20 (kepab); -2  * 0.5 (deposit).");

Match the numbers to be multiplied by regex with groups - use String.replace function, there may be an overload with a callback that can help you.

answered by user matthew44
function mm(text) {

    let pattern = /-?\d+[ *.]+-?[\d].[\d]+/g;

    text = text.replace(pattern, (match) =>
        let numbers = match.split('*').filter(x => x != '').map(Number);
        return numbers[0] * numbers[1];