Last active
December 20, 2019 13:26
-
-
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
This file contains hidden or 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
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