Last active
August 29, 2015 14:07
-
-
Save gr0uch/c9565e1de3d361985edc to your computer and use it in GitHub Desktop.
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
// ==UserScript== | |
// @name Word Filter | |
// @description Replace words with other words. | |
// @namespace http://daliwa.li | |
// @include * | |
// @version 1.0.0 | |
// @grant none | |
// ==/UserScript== | |
'use strict'; | |
// word filter, where keys are regular expressions | |
const wordFilter = { | |
'Suzy Bao': '♥ Waifu Bao ♥', | |
'suzyOcean': '♥ waifuOcean ♥', | |
'raumkraehe': '♥ raumschwein ♥' | |
}; | |
// x=============================x | |
// | do not edit below this line | | |
// x=============================x | |
init(); | |
function init () { | |
var node; | |
var walk = document.createTreeWalker( | |
document.body, NodeFilter.SHOW_TEXT, null, false); | |
var mutationFilter = new MutationObserver(function (mutations) { | |
mutations.forEach(mutationHandler); | |
}); | |
// first walk the initial state of the DOM | |
while (node = walk.nextNode()) { | |
replaceWords(node); | |
} | |
// then observe changes on the DOM | |
mutationFilter.observe(document.body, { | |
childList: true, | |
characterData: true, | |
subtree: true | |
}); | |
} | |
function mutationHandler (mutation) { | |
var i; | |
var node; | |
var walk; | |
if (mutation.type === 'childList') { | |
for (i = 0; i < mutation.addedNodes.length; i++) { | |
node = mutation.addedNodes[i]; | |
if (node.nodeType === 1) { | |
walk = document.createTreeWalker( | |
node, NodeFilter.SHOW_TEXT, null, false); | |
while (node = walk.nextNode()) { | |
replaceWords(node); | |
} | |
} else if (node.nodeType === 3) { | |
replaceWords(node); | |
} | |
} | |
} else if (mutation.type === 'characterData') { | |
replaceWords(mutation.target); | |
} | |
} | |
function replaceWords (node) { | |
var key; | |
var regExp; | |
for (key in wordFilter) { | |
regExp = new RegExp('(\\b|^)' + key + '(\\b|$)', 'ig'); | |
(node.nodeValue.match(regExp) || []).forEach(function(match) { | |
node.nodeValue = node.nodeValue.replace(match, function (value) { | |
return replaceValue(value, wordFilter[key]); | |
}); | |
}); | |
} | |
} | |
function replaceValue (value, replacement) { | |
var firstCharacter = value.charAt(0); | |
if (firstCharacter === firstCharacter.toLowerCase()) { | |
replacement = replacement.charAt(0).toLowerCase() + replacement.slice(1); | |
} | |
else if (firstCharacter === firstCharacter.toUpperCase()) { | |
replacement = replacement.charAt(0).toUpperCase() + replacement.slice(1); | |
if (value === value.toUpperCase()) { | |
replacement = replacement.toUpperCase(); | |
} | |
} | |
return replacement; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment