Andrey Osiyuk
Andrey Osiyuk

Reputation: 366

How to make RegExp work? (Google Apps Script)

Trying write search function that will search for few different formats of numbers (examples: +############, # (###) ###-##-##, ########### and etc. ) and format(replace) in one format (+7(###)###-##-##).

note: format means replace string with string that properly formated, but not use formating setting

Function. It's right now lacks of replace functionality.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();

var history = ss.getSheetByName('sheetname');
ss.setActiveSheet(history);

for(i = 1; i <= history.getMaxRows(); i += 1) {
  var r = history.getRange('D' + i)

  var regexp = RegExp ('/+\d{11}', 'g')

  Logger.log("Value: " + r.getValue())

  if (regexp.exec(r.getValue()) !== null ) {
      Logger.log('true')
    } else {
      Logger.log('false')
    }
}

Logger output:

Line 1: Value: +#(###)###-##-##
Line 2: false
Line 3: Value: +###########
Line 4: false
Line 5: Value: +###########
Line 6: false

regexp.exec(r.getValue()) returns null.

I except get true on line 4 and 6.

Upvotes: 0

Views: 5674

Answers (1)

Andrey Osiyuk
Andrey Osiyuk

Reputation: 366

Problem was in var regexp = RegExp ('/+\d{11}', 'g'). When i wrote var regexp = /\+\d{11}/ it starts work.

Thank you to ctwheels. He wrote regex which was finding all formats and replaced with right one.

Final solution

for(i = 1; i <= history.getMaxRows(); i += 1) {

  var r = history.getRange('D' + i);
  var regexp = /\+?(\d{1,2}?)(?: *\()?(\d{3})(?:\) *)?(\d{3})-?(\d{2})-?(\d{2}\b)/
  var replace = '+7($2)$3-$4-$5';

  if (regexp.exec(r.getValue()) !== null ) {
    var repla = r.getValue().replace(regexp, replace)
    r.setValue(repla)
  }
}

Upvotes: 1

Related Questions