Last active
January 1, 2016 23:38
-
-
Save romaricpascal/8217467 to your computer and use it in GitHub Desktop.
Bookmarklet to export HSBC statements to CSV
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 () { | |
var months = { | |
'Jan': '01', | |
'Feb': '02', | |
'Mar': '03', | |
'Apr': '04', | |
'May': '05', | |
'Jun': '06', | |
'Jul': '07', | |
'Aug': '08', | |
'Sep': '09', | |
'Oct': '10', | |
'Nov': '11', | |
'Dec': '12' | |
}; | |
function locateTextNode(text) { | |
var xPathResult = document.evaluate('//text()[contains(.,\'' + text + '\')]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); | |
return xPathResult.singleNodeValue | |
} | |
function nextElement(elem) { | |
do { | |
elem = elem.nextSibling | |
} while (elem && elem.nodeType !== 1); | |
return elem | |
} | |
var dateFormat = /(.{2}) (.{3})( ..(.{2}))?$/; | |
function readStatementDate() { | |
var label = locateTextNode('Statement date:'); | |
var statementDate = nextElement(label.parentNode.parentNode).textContent.trim(); | |
var result = dateFormat.exec(statementDate); | |
return { | |
day: result[1], | |
month: months[result[2]], | |
year: result[4] | |
} | |
} | |
var statementDate = readStatementDate(); | |
function parseDate(tr) { | |
var value = tr.children[0].textContent.trim(); | |
var tokens = dateFormat.exec(value); | |
return [ | |
tokens[1], | |
months[tokens[2]], | |
statementDate.year | |
].join('/') | |
} | |
function parseAmount(tr) { | |
var out = tr.children[3].textContent.trim(); | |
var amountIn = tr.children[4].textContent.trim(); | |
if (out) { | |
return '-' + out | |
} | |
return amountIn | |
} | |
function parseDescription(tr) { | |
return tr.children[2].textContent.trim() | |
} | |
function parseRow(tr) { | |
var parsed = [ | |
parseDate(tr), | |
parseAmount(tr), | |
parseDescription(tr) | |
]; | |
return parsed | |
} | |
function formatCSV(result, row) { | |
if (row[1]) { | |
return result += row.join(',') + '\n' | |
} else { | |
return result | |
} | |
} | |
function generateFileName() { | |
return statementDate.year + statementDate.month + statementDate.day + '.csv' | |
} | |
function download() { | |
var dataURL = 'data:text/csv;charset=utf8;base64,' + btoa(csv); | |
var downloadLink = document.createElement('a'); | |
downloadLink.setAttribute('download', generateFileName()); | |
downloadLink.href = dataURL; | |
var clickEvent = document.createEvent('MouseEvent'); | |
clickEvent.initEvent('click', true, true); | |
downloadLink.dispatchEvent(clickEvent) | |
} | |
var rows = document.querySelectorAll('[summary] tbody tr'); | |
var csv = Array.prototype.map.call(rows, parseRow).reduce(formatCSV, ''); | |
download(csv) | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment