For extensive Google Docs, manually converting straight to smart quotes is inefficient. This report offers an automated solution using Google Apps Script, saving time and effort.
You might find yourself needing to convert straight quotes (both single and double) to smart quotes in Google Docs. For small documents with a limited number of quotes, this can be done manually with minimal effort. However, when dealing with extensive documents and numerous quotes, the manual process becomes time-consuming and inefficient. This report presents a solution to automate this conversion using Google Apps Script, significantly reducing the processing cost for larger projects.
Create a new Google Document and insert the following sample text. This text includes both single and double straight quotes.
'sample's text' sample's text "sample's text"
Then, open the script editor in Google Apps Script.
Copy and paste the following script into the script editor and save it.
function myFunction() {
const obj = [
{ from: `'`, to: { opening: `‘`, closing: `’` } },
{ from: `"`, to: { opening: `“`, closing: `”` } },
];
const body = DocumentApp.getActiveDocument().getBody();
obj.forEach(({ from, to: { opening, closing } }) => {
let s;
while ((s = body.findText(`\\B${from}.*?${from}\\B`, s))) {
const start = s.getStartOffset();
const end = s.getEndOffsetInclusive();
const text = s.getElement().asText();
text.insertText(end + 1, closing).insertText(start + 1, opening);
text.deleteText(end + 1, end + 1).deleteText(start, start);
}
});
}
In this script, the following steps are run:
- Search for text enclosed by single and double quotes, such as
'sample's text'
and"sample's text"
. - Insert opening and closing smart quotes immediately to the right of the first character and at the end of the found text.
- Delete the original straight quotes.
This flow allows for the conversion of straight quotes to smart quotes without altering the attributes of the text in Google Docs.
Run myFunction
from the script editor. You'll see that both the single and double straight quotes in the sample text have been converted to smart quotes.
From
To
- This script was used as an answer to a question on Stackoverflow. Ref