Home > Software design >  Extract all numbers and multiply
Extract all numbers and multiply

Time:02-03

I am using Google App Script..

var string = "Test 11x Test22x Test 33x";
var multiplier = 4;

What I want to do is extract all numbers from string and multiply them by the multiplier.. so the desired output should be "Test 44x Test88x Test 132x"

I tried

var pattern = /(\d )[^0-9]*/g;
var result = pattern.exec(text);

but it is returning only the first set of numbers.. How do I return all numbers and then multiply them, please?

CodePudding user response:

You can do it all in a String.replace() call passing each match to a replacer function.

function multiplyDigits(string, multiplier) {
  const multiply = match => match * multiplier;

  return string.replace(/\d /g, multiply)
}

const string = "Test -11x Test22x Test 33x";
const multiplier = 4;

const result = multiplyDigits(string, multiplier);

console.log(result);
// Test 44 Test 88 Test 132

CodePudding user response:

Extract and Multiply

function extractandmult() {
  let s = "Test 11 Test 22 Test 33";
  let t = s.split(' ').map(e => {
    let u = parseInt(e);
    if(!isNaN(u)) {
      return u * 4;
    } else {
      return e;
    }
  })
  Logger.log(t);
}

Execution log
4:04:23 PM  Notice  Execution started
4:04:23 PM  Info    [Test, 44.0, Test, 88.0, Test, 132.0]
4:04:24 PM  Notice  Execution completed

Changed my mind it's actually pretty easy

function extractandmult() {
  let s = "Test 11x Test22x Test 33x";
  let a = s.match(/\d /g).slice();
  a.forEach(e => s = s.replace(e, e * 4));
  Logger.log(s);
}


Execution log
4:23:33 PM  Notice  Execution started
4:23:32 PM  Info    Test 44x Test88x Test 132x
4:23:33 PM  Notice  Execution completed

CodePudding user response:

Here is my old trick for such cases:

var string = "Test 11x Test22x Test 33x";
var multiplier = 4;

string.match(/\d /g).forEach(x => string = string.split(x).join(x * multiplier));

console.log(string); // --> Test 44x Test88x Test 132x

  •  Tags:  
  • Related