Reputation: 167
I am trying to replace a piece of String like:
1.Manager 22yo with option C. 2.Employee 455eur (...) 3.Product
with
- Manager 22yo with option C.
- Employee 455eur
- 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!
Upvotes: 0
Views: 44
Reputation: 201358
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?
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));
}
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.When this script is used, the following result is obtained.
1.Manager 22yo with option C. 2.Employee 455eur (...) 3.Product
1.Manager 22yo with option C.
2.Employee 455eur (...)
3.Product
Upvotes: 1