Home > Enterprise >  Google Script (JS) Regex - add additional String in matching places
Google Script (JS) Regex - add additional String in matching places

Time:11-24

I am trying to replace a piece of String like:

1.Manager 22yo with option C. 2.Employee 455eur (...) 3.Product

with

  1. Manager 22yo with option C.
  2. Employee 455eur
  3. Product

I tried doing that:

function enterNewLineForAnswers(){


 var body = DocumentApp.getActiveDocument()
      .getBody();

body.replaceText("[0-9]{1,2}[/.]{1}","\n"   '$&')
}

but it gives me escaped '$&' chars instead of the number found by regex. Can you help me find another approach? Thanks!

CodePudding user response:

In your script and situation, I think that body.replaceText("[0-9]{1,2}[/.]{1}","\n" '$&') cannot be used. This has already been discussed in the comment. So, in order to achieve your goal, how about the following sample script?

Sample script:

function enterNewLineForAnswers() {
  var body = DocumentApp.getActiveDocument().getBody();
  var search = "([0-9]{1,2}[/.]{1})";
  var s = body.findText(search);
  var values = [];
  while (s) {
    var text = s.getElement().asText();
    var r = new RegExp(search, "g");
    var k = `{{sample${values.length}}}`;
    values.push([k, text.getText().replace(r, "\n$1")]);
    text.setText(k);
    s = body.findText(search, s);
  }
  if (values.length == 0) return;
  values.forEach(e => body.replaceText(...e));
}
  • In this sample script, first, the value like 1.Manager 22yo with option C. 2.Employee 455eur (...) 3.Product is searched and create the replacing texts using replace of Javascript and your regex. And, the texts are replaced. I thought that by this flow, your goal is achieved.

Testing:

When this script is used, the following result is obtained.

From:

1.Manager 22yo with option C. 2.Employee 455eur (...) 3.Product

To:

1.Manager 22yo with option C. 
2.Employee 455eur (...) 
3.Product

References:

  • Related