Home > front end >  Can't figure out what I did wrong in this encryption web app. Why it is changing the wrong lett
Can't figure out what I did wrong in this encryption web app. Why it is changing the wrong lett

Time:01-19

So, I made this little web app to encrypt text, but I don't get why is changing wrong letters.

/* REMOVE */

var defaultDiacriticsRemovalMap  = {
    "a": "ai",
    "e": "enter",
    "i": "imes",
    "o": "ober",
    "u": "ufat"
};

  

function removeDiacritics(str) {
    for (let char in defaultDiacriticsRemovalMap ) {
        str = str.replace(new RegExp(char, 'g'), defaultDiacriticsRemovalMap [char]);
    }
    return str;
}

function replaceText() {
    var str = document.getElementById('original-text').value;
    document.getElementById('result-text').value = removeDiacritics(str);
}

/* RETURN */
function returnDiacritics(str) {
    for (let char in defaultDiacriticsReturnMap) {
        str = str.replace(new RegExp(char, 'g'), defaultDiacriticsReturnMap[char]);
    }
    return str;
}

var defaultDiacriticsReturnMap = {
    "ai": "a",
    "enter": "e",
    "imes": "i",
    "ober": "o",
    "ober": "o"
};

function returnText() {
    var str = document.getElementById('original-text').value;
    document.getElementById('result-text').value = returnDiacritics(str);
}

/* COPY TEXT */
function copyText() {
    var copyText = document.getElementById("result-text");
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    navigator.clipboard.writeText(copyText.value);
    alert("Copied the text: "   copyText.value);
}
<textarea id="original-text"></textarea>
<button onclick="replaceText()">Encrypt text</button>
<button onclick="returnText()">Decrypt text</button>
<textarea id="result-text"></textarea>
<button onclick="copyText()">Copy text</button>

So now I can return the text to its original state. But now I have a new problem. I put "aeiou" as input to test it, but when the text is replaced, the result text, changes the "i" in the "ai" value for "imes", so the result comes as "aimesenterimesoberufat", as you can see in the next image...

enter image description here

Buuuut... when I reverse the changes now does something similar to the above. enter image description here

I really don't get what is happening here. Thanks for all your help!

CodePudding user response:

Your code is replacing previous replacements strings on subsequent iterations. Instead, call String#replace with a single regular expression (that combines all the characters to match using |, which means or).

For example:

function removeDiacritics(str) {
    return str.replace(new RegExp(Object.keys(defaultDiacriticsRemovalMap).join('|'), 'g'),
        c => defaultDiacriticsRemovalMap[c]);
}
  • Related