Skip to content

Instantly share code, notes, and snippets.

@nickscript0
Last active December 20, 2019 13:26
Show Gist options
  • Save nickscript0/4ab9c666af7a792013073a08292227df to your computer and use it in GitHub Desktop.
Save nickscript0/4ab9c666af7a792013073a08292227df to your computer and use it in GitHub Desktop.
Bookmarklet: Finds all strings that match '<number> mpg' and suffixes them with the l/100km conversion
javascript: (function () {
function convert(currentElement) {
if (!currentElement.textContent) return;
/*
* Match mpg strings with negative lookahead for the l/100km conversion string
* to avoid duplicating the conversion when run multiple times.
* E.g. "N.N mpg" not followed by " (N.N l/100km)"
*/
const mpgRegex = /(\d*(\.\d+)?)(\s)*mpg(?!\s\(\d+\.\d+\sl\/100km\))/gi;
const currentText = currentElement.textContent;
if (mpgRegex.test(currentText)) {
const newText = currentText.replace(
mpgRegex,
(match, mpgText) => {
const mpg = parseFloat(mpgText);
if (!isNaN(mpg)) {
const lp100 = 235.21 / mpg;
const newValue = `${match} (${lp100.toFixed(1)} l/100km)`;
return newValue;
}
return match;
}
);
console.log(`Updated ${newText}`);
currentElement.textContent = newText;
}
}
function textNodes(el) {
var n, a = [], walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false);
while (n = walk.nextNode()) a.push(n);
return a;
}
textNodes(document).forEach(n => convert(n));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment