I need help with transforming date formats in Google Docs using Apps Script. While working with date format changes in Google Sheets is pretty straightforward, I’m completely lost when it comes to doing the same thing in Google Docs.
I want to scan through an entire document that has multiple pages and find all dates that look like 2024-03-15 (year-month-day format) and change them to 15/03/2024 (day/month/year format).
I know there’s an Apps Script option available in Google Docs, but I have no clue where to begin. Is this even possible to do? I’m familiar with how to handle this in Sheets but Docs seems totally different.
Basically I want to use a regex pattern like (\d{4})-(\d{2})-(\d{2}) to find the dates and replace them with \3/\2/\1 format throughout the entire document text.
Had this exact issue a few weeks ago. Your regex works fine for basic text, but Apps Script needs extra escaping - use (\\d{4})-(\\d{2})-(\\d{2}) with four backslashes. I’d add a quick date validation before doing the replacement. Just check if the matched string is actually a valid date. Also throw it in a try-catch block - corrupted docs can make the script fail without any error message. One heads up: replaceText goes through the whole document at once. If you’ve got tons of dates, maybe chunk it up or run it when things aren’t busy. Nice thing is it handles footnotes automatically, which beats doing it by hand.
Yeah, you can definitely do date conversion in Google Docs with Apps Script. It’s different from Sheets since you’re working with the document body and need replaceText with regex. Here’s what worked for me: Get your document with DocumentApp.getActiveDocument() or DocumentApp.openById(). Then use body.replaceText() - it takes regex patterns directly. Your regex looks right, so try body.replaceText(‘(\d{4})-(\d{2})-(\d{2})’, ‘$3/$2/$1’) to flip the format. Two things I learned the hard way: You need double backslashes in Apps Script strings (hence \d instead of \d), and use dollar signs for group references instead of backslashes. The method hits the whole document at once, so don’t worry about multiple pages.
Been there with huge document batches. Apps Script gets messy when you need this across multiple docs or want recurring date fixes.
Regex works (like others said), but I learned manual scripts become nightmares when you need regular runs across team documents.
Automated workflows saved me - they monitor Google Docs for changes and apply date formatting instantly. No more manual scripts or remembering to process new docs.
You can build the same regex logic visually and add conditions like date validation or skipping sections. Handles edge cases better too - processing specific paragraphs or excluding header dates.
Workflows also batch process entire folders and send completion notifications. Way cleaner than maintaining Apps Script code.
Latenode makes Google Docs automation simple with visual builders. Same regex power, better error handling and monitoring.
Apps Script works, but you’ll hit walls fast. What about different date formats? Multiple documents? Integration with other systems?
I’ve tried this approach - automation platforms crush custom scripts every time. Set up workflows that watch your Google Docs and fix date formats automatically when files change.
You get a visual builder instead of debugging regex hell. Plus you can chain actions - send notifications when dates update, log changes to spreadsheets, batch process multiple docs.
We built something like this for our team’s docs. Everything processes automatically when shared or modified. Zero manual script running.
Latenode nails this Google Docs automation with drag-and-drop. Build regex logic visually, add error handling without code.
Estás intentando convertir formatos de fecha en Google Docs usando Apps Script. Tu script usa replaceText() con una expresión regular, pero estás encontrando problemas con fechas en diferentes partes del documento (cabezados, pies de página, tablas, etc.).
Step-by-Step Guide:
Preparación: Antes de comenzar, realiza una copia de seguridad de tu documento de Google Docs. Esto es crucial ya que no hay un mecanismo de deshacer integrado en Apps Script para las operaciones replaceText().
Acceso al Documento: Obtén una referencia al documento de Google Docs usando el ID del documento o utilizando DocumentApp.getActiveDocument() si estás ejecutando el script directamente en el documento.
const doc = DocumentApp.getActiveDocument(); // O DocumentApp.openById(docId);
const body = doc.getBody();
Expresión Regular: Tu expresión regular (\d{4})-(\d{2})-(\d{2}) es correcta para encontrar fechas en el formato AAAA-MM-DD. Sin embargo, en Apps Script, necesitas escapar las barras invertidas: (\\\\d{4})-(\\\\d{2})-(\\\\d{2}). La sustitución $3/$2/$1 también es correcta.
Reemplazo del Texto Principal: Aplica replaceText() al cuerpo principal del documento para cambiar el formato de las fechas. Envuelve esto en un bloque try...catch para manejar posibles errores.
try {
const numReplacements = body.replaceText('(\\\\d{4})-(\\\\d{2})-(\\\\d{2})', '$3/$2/$1');
Logger.log(`Se reemplazaron ${numReplacements} ocurrencias en el cuerpo del documento.`);
} catch (error) {
Logger.log(`Error al reemplazar el texto en el cuerpo del documento: ${error}`);
}
Tratamiento de Cabeceras y Pies de Página: Las fechas en las cabeceras y pies de página requieren un tratamiento separado. Debes acceder a los elementos de cabecera y pie de página y aplicar replaceText() a cada uno de ellos.
const sections = doc.getBody().getSections();
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
const header = section.getHeader();
const footer = section.getFooter();
try {
const headerReplacements = header.replaceText('(\\\\d{4})-(\\\\d{2})-(\\\\d{2})', '$3/$2/$1');
Logger.log(`Se reemplazaron ${headerReplacements} ocurrencias en el encabezado de la sección ${i + 1}.`);
const footerReplacements = footer.replaceText('(\\\\d{4})-(\\\\d{2})-(\\\\d{2})', '$3/$2/$1');
Logger.log(`Se reemplazaron ${footerReplacements} ocurrencias en el pie de página de la sección ${i + 1}.`);
} catch (error) {
Logger.log(`Error al reemplazar el texto en la sección ${i + 1}: ${error}`);
}
}
Tratamiento de Tablas: Para las fechas dentro de las tablas, debes iterar sobre cada tabla, fila y celda, y aplicar replaceText() a cada celda individualmente.
const tables = body.getTables();
for (let i = 0; i < tables.length; i++) {
const table = tables[i];
const numRows = table.getNumRows();
for (let j = 0; j < numRows; j++) {
const row = table.getRow(j);
const numCells = row.getNumCells();
for (let k = 0; k < numCells; k++) {
const cell = row.getCell(k);
try {
const cellReplacements = cell.replaceText('(\\\\d{4})-(\\\\d{2})-(\\\\d{2})', '$3/$2/$1');
Logger.log(`Se reemplazaron ${cellReplacements} ocurrencias en la celda (${j + 1}, ${k + 1}) de la tabla ${i + 1}.`);
} catch (error) {
Logger.log(`Error al reemplazar el texto en la celda (${j + 1}, ${k + 1}) de la tabla ${i + 1}: ${error}`);
}
}
}
}
Validación (opcional): Para evitar la conversión de cadenas que no son fechas, puedes agregar una validación antes del reemplazo. Esto requiere una función adicional para verificar si la cadena coincide con el formato de fecha esperado.
Common Pitfalls & What to Check Next:
Formato de Fecha: Asegúrate de que todas las fechas en tu documento siguen el formato AAAA-MM-DD. El script solo convertirá las fechas que coincidan con este patrón.
Errores de la API: Revisa los logs de Apps Script para identificar cualquier error que pueda haber ocurrido durante el proceso.
Complejidad del Documento: Para documentos muy grandes, considera dividir el proceso en partes más pequeñas para mejorar el rendimiento.
Texto con coincidencias parciales: Tu expresión regular podría coincidir con partes del texto que no son fechas (ej., números de identificación). Refina la expresión regular si es necesario para evitar cambios no deseados.
Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!
hit this exact issue yesterday! replacetext works great but watch out - it won’t touch dates inside text boxes or drawings. always backup your doc first since there’s no undo after the script runs.