I'm looking to replace all characters that appear in a webpage with another character, for example replace 'a' with 'A'. Except for one caveat which I will further explain, I currently have this working well with the following code:
function replaceTextOnPage(){
getAllTextNodes().forEach(function(node){
let map = new Map()
map.set('さ', ['さ', 'サ'])
node.nodeValue = node.nodeValue.replace(new RegExp(quote(map.get(node.)[0]), 'g'), map.get('さ')[1]);
});
function getAllTextNodes(){
var result = [];
(function scanSubTree(node){
if(node.childNodes.length)
for(var i = 0; i < node.childNodes.length; i++)
scanSubTree(node.childNodes[i]);
else if(node.nodeType == Node.TEXT_NODE)
result.push(node);
})(document);
return result;
}
function quote(str){
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
}
Now if we take a look at the upper portion, the second function
getAllTextNodes().forEach(function(node){
let map = new Map()
map.set('a', ['a', 'A'])
node.nodeValue = node.nodeValue.replace(new RegExp(quote(map.get('a')[0]), 'g'), map.get('a')[1]);
});
I use a map (for efficiency purposes if using this for replacements of many different characters). The way the code is written here works as I want - effectively replaces all 'a' with 'A'. map.get('a')[0]
gets the value associated with 'a', which is an array at the 0 index, or 'a'. This is the value to be replaced. map.get('a')[1]
then gets the value at the 1 index of the array, or 'A'. The value to replace with.
My question is making this process "generic" so to speak. Ultimately I will be swapping all values of around 60 different characters (for Japanese, but can be thought of as me swapping every distinct lower case with upper-case and vice-versa). I was thinking, as each character (current key) is being traversed over, that key's respective map value would replace the key. Doing this iteratively for each of the getAllTextNodes with O(1) map lookup time.
I essentially need a way to call the current whatever character is being currently iterated over. I have tried map.get(node.nodeValue)
as well as map.get(node.textContent)
, but neither worked.
Any help is greatly appreciated!!