user1592380
user1592380

Reputation: 36337

Apps script Regex: SyntaxError: Invalid quantifier

enter image description here

Based on https://www.plivo.com/blog/Send-templatized-SMS-from-a-Google-spreadsheet-using-Plivo-SMS-API/ I have the following code:

function createMessage(){
  data = {
    "SOURCE" : "+1234567890",
    "DESTINATION" : "+2345678901",
    "FIRST_NAME" : "Jane",
    "LAST_NAME" : "Doe",
    "COUPON" : "DUMMY20",
    "STORE" : "PLIVO",
    "DISCOUNT" : "20",
  }

  template_data = "Hi   , your coupon code for discount of % purchase at  is "
  Logger.log(data);

  for (var key in data) {
    Logger.log(key);

    if (data.hasOwnProperty(key)) {
      template_data = template_data.replace(new RegExp('+key+', 'gi'),data[key]); // error here
    }
  }
  Logger.log(template_data);
  return template_data;
}

When I run createMessage I get :

SyntaxError: Invalid quantifier +. (line 57, file "Code")

What am I doing wrong? How can I fix this?

Upvotes: 3

Views: 831

Answers (1)

Anton Dementiev
Anton Dementiev

Reputation: 5716

The leading '+' in your regular expression is what causes the problem. '+' is the quantifier that specifies how many patterns should be matched (in this case, one or more). So when you have the quantifier without the pattern, it's like matching one or more of 'nothing'.

Upvotes: 2

Related Questions