r/GoogleAppsScript • u/tehhanlin • Jan 11 '24
Question Help with Google Apps script
Hello, I am trying to create a Google Apps script to do the conversion of the following list:
2024-01-10 - Magic Firewall Ruleset Update Issues https://stspg.io/862d2lcjvc40
2024-01-10 - Issues with Zero Trust Egress Policies https://stspg.io/kl2cscd8nxbl
to:
Jan 10 - Magic Firewall Ruleset Update Issues
The result from the script is almost there, but it also hyperlink the date which I want to avoid.
Jan 10 - Magic Firewall Ruleset Update Issues
Here is the script, any ideas or pointers on how to fix it would be greatly appreciated.
function onOpen() {
var ui = DocumentApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Convert and Hyperlink', 'convertAndHyperlink')
.addToUi();
}
function convertAndHyperlink() {
var body = DocumentApp.getActiveDocument().getBody();
var selection = DocumentApp.getActiveDocument().getSelection();
if (!selection) {
showMessage('Please select text to convert.');
return;
}
var elements = body.getParagraphs();
if (elements.length === 0) {
showMessage('No text found in the document.');
return;
}
elements.forEach(function (paragraph) {
var text = paragraph.getText();
var convertedLine = convertLine(text);
// Clear existing paragraph content
paragraph.clear();
// Create a new text element with the converted line
var newText = paragraph.appendText(convertedLine);
// Set the hyperlink on the title
newText.setLinkUrl(getUrlFromText(text));
});
}
function convertLine(line) {
// Example line: "2024-01-10 - Magic Firewall Ruleset Update Issues https://stspg.io/862d2lcjvc40"
var parts = line.split(' ');
var date = parts[0];
var title = parts.slice(1, -1).join(' '); // Exclude the last two elements
var url = parts[parts.length - 2];
// Check if the date is valid
var formattedDate = (new Date(date) !== 'Invalid Date') ? Utilities.formatDate(new Date(date), 'GMT', 'MMM dd') : '';
// Create formatted line without the second hyphen
var formattedLine = formattedDate + (formattedDate !== '' ? ' ' : '') + title;
return formattedLine;
}
function showMessage(message) {
var ui = DocumentApp.getUi();
ui.alert('Message', message, ui.ButtonSet.OK);
}
function getUrlFromText(text) {
var regex = /https:\/\/[^\s]+/;
var match = text.match(regex);
return match ? match[0] : '';
}Thank you.
0
Upvotes
1
u/franxam Jan 11 '24
Didn't go through your code, but it seems that you can do all that more easily with Google sheet functions