Here is some code that evaluates every word in a paragraph. He underlines every word in the third paragraph, which is not underlined. For example, the code receives the third paragraph. You will need to adjust the code according to your criteria. The code assumes that if the first letter of the word is underlined, the entire word is underlined. Each word has a bold font with a start and end index.
function findAndBold() {
var allParagraphs,bodyElement,endPosition,lengthOfThisWord ,numberOfWordsInPara ,
paragraphAsString,remainingTxtInParagraph,startPosition,text ,theParagraph;
bodyElement = DocumentApp.getActiveDocument().getBody();
allParagraphs = bodyElement.getParagraphs();
theParagraph = allParagraphs[2];
text = theParagraph.editAsText();
paragraphAsString = text.getText();
startPosition = 0;
endPosition = 0;
remainingTxtInParagraph = paragraphAsString;
lengthOfThisWord = 0;
numberOfWordsInPara = 0;
while (remainingTxtInParagraph.length > 0) {
Logger.log("remainingTxtInParagraph: " + remainingTxtInParagraph.length);
numberOfWordsInPara ++;
lengthOfThisWord = remainingTxtInParagraph.indexOf(" ");
Logger.log("lengthOfThisWord: " + lengthOfThisWord);
if (lengthOfThisWord > -1) {
endPosition = startPosition + lengthOfThisWord;
Logger.log("startPosition: " + startPosition);
Logger.log("endPosition: " + endPosition);
} else {
lengthOfThisWord = remainingTxtInParagraph.length;
Logger.log("lengthOfThisWord: " + lengthOfThisWord);
endPosition = startPosition + lengthOfThisWord - 1;
Logger.log("final end position: " + endPosition);
Logger.log("startPosition: " + startPosition);
};
remainingTxtInParagraph = remainingTxtInParagraph.substr(lengthOfThisWord + 1);
Logger.log("remainingTxtInParagraph: " + remainingTxtInParagraph.length);
if (!text.isUnderline(startPosition)) {
text.setBold(startPosition, endPosition, true);
};
startPosition = startPosition + lengthOfThisWord + 1;
Logger.log("next iteration startPosition: " + startPosition);
Logger.log(" ");
};
Logger.log("numberOfWordsInPara: " + numberOfWordsInPara);
}
The code uses a combination of JavaScript string methods, the JavaScript string length property, and the Script text class methods.
source
share