I have implemented GAS in my Google document, but I cannot replace regular expressions.

Asked 2 years ago, Updated 2 years ago, 70 views

The script below does not work as intended.
I'm going to search for the sentence that starts with ★ and display it as it is, but I can't do this, so could you please let me know?

For example, I would like to replace the document as follows.
In other words, you want to add a tag.

before replacement:

 ★ ah jf pew

after substitution:

<div>ajf pew</div>

Current State Script:

function myFunction(){
  var doc = DocumentApp.getActiveDocument()
  varbody=doc.getBody();
  body.replaceText("★.*", '$&');
}

regular-expression google-apps-script

2022-09-30 20:13

2 Answers

replaceText("★.*", '$&')
I think this will only replace the pattern that starts with with $&.


2022-09-30 20:13

I see, String.replace() of GAS replaces $& with the entire matched string.I didn't know.
However, DocumentApp.getActiveDocument().getBody().replaceText() does not seem to have that function.
Then why don't you try it this way?
There might be another problem.

function myFunction(){
  var doc = DocumentApp.getActiveDocument();
  varbodyText=doc.getBody().getText();
  var replacedText=bodyText.replace(/(★\S*)/g, "<div>$&/div>");
  doc.getBody().setText(replacedText);
}


2022-09-30 20:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.