-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCode.gs
60 lines (52 loc) · 1.87 KB
/
Code.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Convert links in selection', 'convertSelection')
.addItem('Convert links in current sheet', 'convertSheet')
.addItem('Convert links in spreadsheet', 'convertSpreadsheet')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
function convertSelection() {
convert('selection', SpreadsheetApp.getSelection().getActiveRangeList().getRanges());
}
function convertSheet() {
convert('current sheet', [SpreadsheetApp.getActiveSheet().getDataRange()]);
}
function convertSpreadsheet() {
convert('spreadsheet', SpreadsheetApp.getActiveSpreadsheet().getSheets().map(function (sheet) { return sheet.getDataRange() }));
}
function convert(description, ranges) {
var replacements = [];
for(var i=0; i<ranges.length; i++) {
var range = ranges[i];
var values = range.getValues();
for (var j=0; j<range.getHeight(); j++) {
for (var k=0; k<range.getWidth(); k++) {
var match = values[j][k].toString().match(/^\[\s*([^\]]+)\]\(([^\)]+)\)/);
if (match) {
var targetCell = range.getCell(j+1, k+1);
var label = match[1];
var url = match[2];
var newValue = "=hyperlink(\"" + url + "\", \"" + label + "\")";
var replacement = [targetCell, newValue];
replacements.push(replacement);
}
}
}
}
// batch updates so the undo system treats it as a single change
for(var i=0; i<replacements.length; i++) {
var targetCell = replacements[i][0];
var newValue = replacements[i][1];
targetCell.setFormula(newValue);
}
SpreadsheetApp.flush();
var n = replacements.length;
SpreadsheetApp.getUi().alert(
n > 0
? "Replaced " + n + " Periscope hyperlink" + (n == 1 ? "" : "s") + " in " + description + " with GSheets equivalent."
: "No Periscope hyperlinks found in " + description + "."
);
}