limonvnx
limonvnx

Reputation: 83

Replacing numbers in a string with a modified number using regex - Javascript

I'm new to javascript so apologies if I've missed something simple. I'm working on a script to take a string from one cell in Sheets, add VAT at 5% to any applicable numbers and output the amended string in a new cell. I'm happy with the regex capturing the numbers I need, but getting the amended string correct is proving tricky.

So far the script looks like this:

function strReplace() {
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheet = ss.getActiveSheet();
   var str = sheet.getRange(4,2).getValue(); // A cell with a string like this: "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87"

   var regex = /\d{1,8}(?:\.\d{1,8})/g  // Regex to ignore numbers greater than 8 digits, including decimals

   var newStr = str.match(regex);


   for (var x = 0; x < newStr.length; x++) {

    var newRates = newStr[x]*1.05;
    var output = str.replace(newStr, newRates)

    sheet.getRange(4,3).setValue(output);

    }                   
  }  

I've tried a bunch of variations but with no success. I feel there is an easier way to achieve what I'm looking for from what I already have. Any recommendations would be much appreciated.

Thanks!

Upvotes: 2

Views: 90

Answers (2)

Prince Hernandez
Prince Hernandez

Reputation: 3731

basically your solution is very close, you just needed tot assign the str.replace, use the newStr[x] and also wait to end the for to assign it into the cell.

check the sample below.

function strReplace() {

  let str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
  var regex = /\d{1,8}(?:\.\d{1,8})/g

  var newStr = str.match(regex);

  for (var x = 0; x < newStr.length; x++) {
    var newRates = parseFloat(newStr[x]) * 1.05;
    str = str.replace(newStr[x], newRates)
  }

  return str;
}

var replaced = strReplace();

console.log(replaced)

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075199

To do this kind of thing, you use the function callback version of replace:

var str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
var regex = /\d{1,8}(?:\.\d{1,8})/g;  // Regex to ignore numbers greater than 8 digits, including decimals
var output = str.replace(regex, function(match) {
    return 1.05 * match;
});
console.log(output);

You might choose to use parseFloat(match) rather than just using match, which relies on * coercing the string to number.

And you might consider .toFixed(2) on the result to round and format to two places (depending on whether you want to round the way it rounds). For instance:

var str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
var regex = /\d{1,8}(?:\.\d{1,8})/g;  // Regex to ignore numbers greater than 8 digits, including decimals
var output = str.replace(regex, function(match) {
    return (1.05 * match).toFixed(2);
});
console.log(output);

Upvotes: 1

Related Questions