1

I made a function in Google Apps Script that searches for all words in a Google Docs and changes their colors to a desired color. It takes as inputs: the doc ID, the color desired and the word to look for.

However, what I really need is a function that finds all the words that start with a particular string. For example, "change all words that start with # to blue". I tried messing with findText() but had no luck. Any ideas on how to fix the function below to do what I need? Thanks!

Currently, my function looks like this:

 function colorTheWords(findMe,color,documentID) {

  //color input must be formatted in CSS notation like '#ffffff'
  
  //documentID must be formated as text in between ''
  
  //findMe word must be formatted as ''
  
  //open doc
  var document = DocumentApp.openById(documentID);
  var body = document.getBody();
  var foundElement = body.findText(findMe);

  while (foundElement != null) {
    // Get the text object from the element
    var foundText = foundElement.getElement().asText();

    // Where in the Element is the found text?
    var start = foundElement.getStartOffset();
    var end = foundElement.getEndOffsetInclusive();

    // Change the current color to the desired color
    foundText.setForegroundColor(start, end, color);

    // Find the next match
    foundElement = body.findText(findMe, foundElement);
  }

} 
makae90
  • 33
  • 4

2 Answers2

0

You can use regular expressions findText, which will allow you to do this easily. There is an answer to a similar question here:

Regex to check whether string starts with, ignoring case differences

I always use this site to help me to test my regular expressions before adding them to the code. Paste the contents of your document in and then fiddle with your regex until you just select what you need. https://regexr.com/

Dave Cook
  • 617
  • 1
  • 5
  • 17
  • Oh, thanks so much! Could you give me help just a little further though, I think I'm almost there! Sorry, I'm just new to coding in general. I tried the following var searchPattern = new RegExp('^' + findMe, 'i'); var foundElement = body.findText(searchPattern); But then I get no hits. – makae90 Sep 30 '20 at 17:55
0

The main issue you are encountering is that findText does not use normal regular expressions but a flavour called re2. This has some slight variations and restrictions. If you want to find all words that start with a specific string or character, this is the expression you should be using:

#([^\s]+)
halfer
  • 19,824
  • 17
  • 99
  • 186
Mateo Randwolf
  • 2,823
  • 1
  • 6
  • 17
  • Oh my that is awesome! It works so well! Thanks! I did not know about re2, what a great resource you linked! – makae90 Oct 02 '20 at 02:09
  • No worries, glad it help. Please consider accepting /upvoting my answer if it solved your issue so that other users with similar problems find it easily :D – Mateo Randwolf Oct 02 '20 at 06:51