Created
November 5, 2019 14:00
-
-
Save SavchenkoValeriy/4da6819f985797df536a431be101e849 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function onOpen() { | |
const ui = DocumentApp.getUi(); | |
ui.createMenu('SEO') | |
.addItem('Check Keywords', 'findKeywords') | |
.addToUi(); | |
} | |
function makeCaseInsensitive(searchPattern) { | |
// see: https://stackoverflow.com/a/54217083/11582326 | |
return "(?i)" + searchPattern; | |
} | |
function highlight(text, matchedRange) { | |
text.setBackgroundColor(matchedRange.getStartOffset(), | |
matchedRange.getEndOffsetInclusive(), | |
"#FFA500"); | |
} | |
function findKeywordsInParagraph(keyword) { | |
return function (paragraph) { | |
// get paragraph's text that we can modify | |
const Text = paragraph.editAsText(); | |
// turn the given keyword into a search pattern by making it | |
// case insensitive | |
const SearchPattern = makeCaseInsensitive(keyword); | |
// find matching pieces of text | |
var Range = paragraph.findText(SearchPattern); | |
while (Range) { | |
// highlight found match... | |
highlight(Text, Range); | |
// ...and try finding the next one | |
Range = paragraph.findText(SearchPattern, Range); | |
} | |
} | |
} | |
function askUser() { | |
const ui = DocumentApp.getUi(); | |
const response = ui.prompt('Enter your keyword:'); | |
// Process the user's response. | |
if (response.getSelectedButton() == ui.Button.OK) { | |
return response.getResponseText(); | |
} else { | |
// user decided not to give us their keywords :( | |
return null; | |
} | |
} | |
function findKeywords() { | |
const activeDoc = DocumentApp.getActiveDocument(); | |
const paragraphs = activeDoc.getBody().getParagraphs(); | |
// fire up a UI form asking the user for a keyword | |
const keyword = askUser(); | |
// proceed only if user had provided us with a keyword to fetch | |
if (keyword) { | |
// go through the list of paragraphs and highlight | |
// every encountered keyword in them | |
paragraphs.forEach(findKeywordsInParagraph(keyword)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment