Home > Software engineering >  Doesn't work replaceText with regular expression in google scripts
Doesn't work replaceText with regular expression in google scripts

Time:10-10

Found a lot of information, where people say it should work like this:

var id = '/*doc ID here*/';
var doc = DocumentApp.openById(id);
var body = doc.getBody();

var word = 'tototo'
var tempword = 'blablabla';
body.replaceText("\\b" word "\\b", tempword);

But it is not working.

Thу full idea is to find every word LALALA and make it a link, but don't make a link from words LALALAL or ALALALA etc.

function addLinks(word, siteurl) {
    var id = '/*doc ID here*/';
    var doc = DocumentApp.openById(id);
    var body = doc.getBody();

    var tempword = 'ASDFDSGDDKDSL2';
    var element = body.findText(word);
    // var element = body.findText("\\b" word "\\b");
   

    while(element) {
      var start = element.getStartOffset();
    
      var text = element.getElement().asText();
      text.replaceText("\\b" word "\\b", tempword);
      text.setLinkUrl(start, start tempword.length-1, siteurl);
      
      var element = body.findText(word);

    }
    
    body.replaceText(tempword, word);
  }

addLinks('LALALA', 'example.com');

But it makes only one link and not from 1 word as needed, but from 16 letters...

CodePudding user response:

I believe your goal is as follows.

  • You want to search the text of LALALA and replace it with var tempword = 'ASDFDSGDDKDSL2', and then, you want to set the hyperlink to var tempword = 'ASDFDSGDDKDSL2' in Google Document.

In this case, how about the following modification?

Modified script:

Please modify addLinks and test it again.

function addLinks(word, siteurl) {
  var id = '/*doc ID here*/';
  var doc = DocumentApp.openById(id);
  var body = doc.getBody();
  var tempword = 'ASDFDSGDDKDSL2';
  var searchText = "\\b"   word   "\\b";
  var element = body.findText(searchText);
  while (element) {
    var start = element.getStartOffset();
    var text = element.getElement().asText();
    text.replaceText(searchText, tempword);
    text.setLinkUrl(start, start   tempword.length - 1, siteurl);
    element = body.findText(searchText, element);
  }
}
  • In your script,
    • In order to search the next word of word, please use the method of findText(searchPattern, from).
    • In your situation, I thought that the search work might be required to be also used as "\\b" word "\\b".
    • body.replaceText(tempword, word); of the last line in addLinks replace tempword with word.
  • When this modified script is run, the text of LALALA is searched and replaced it with var tempword = 'ASDFDSGDDKDSL2', and then, the hyperlink is set to var tempword = 'ASDFDSGDDKDSL2'. On the other hand, ALALALA is not replaced.

Reference:

  • Related