Search code examples
javascriptreplacealphabet

Javascript reverse alphabet


so I've been messing around with the .replace() function lately and wanted to make it reverse whatever the user inputs. (Aka a -> z, A -> Z, b -> y, B -> Y, ...)

I'm using function stacking, so I just added .replace().replace()... for every letter, but of course that won't work since whenever it hits n, it will begin to reverse all the progress and I end up with an inaccurate translation. Any idea how I can work around this, since as far as I know, JS doesn't have a .reverse() function like Python?

In case you need it, here's my code

//replacing letters
lettertext = ttext.replace("a", "z")
.replace("A", "Z")
.replace("b", "y")
.replace("B", "y")
.replace("c", "x")
.replace("C", "X")
.replace("d", "w")
.replace("D", "W")
.replace("e", "v")
.replace("E", "V")
.replace("f", "u")
.replace("F", "U")
.replace("g", "t")
.replace("G", "T")
.replace("h", "s")
.replace("H", "S")
.replace("i", "r")
.replace("I", "R")
.replace("j", "q")
.replace("J", "Q")
.replace("k", "p")
.replace("K", "P")
.replace("l", "o")
.replace("L", "O")
.replace("m", "n")
.replace("M", "N")
.replace("n", "m")
.replace("N", "M")
.replace("o", "l")
.replace("O", "L")
.replace("p", "k")
.replace("P", "K")
.replace("q", "j")
.replace("Q", "J")
.replace("r", "i")
.replace("R", "I")
.replace("s", "h")
.replace("S", "H")
.replace("t", "g")
.replace("T", "G")
.replace("u", "f")
.replace("U", "F")
.replace("v", "e")
.replace("V", "E")
.replace("w", "d")
.replace("W", "D")
.replace("x", "c")
.replace("X", "C")
.replace("y", "b")
.replace("Y", "B")
.replace("z", "a")
.replace("Z", "A")
.replace("ä", "ß")
.replace("Ä", "ẞ")
.replace("ö", "ü")
.replace("Ö", "Ü")
.replace("ü", "ö")
.replace("Ü", "Ö")
.replace("ß", "ä")
.replace("ẞ", "Ä")

Solution

  • You could take a hash table for the pairs and map new character or the original character if not available in the hash table.

    function replace(string) {
        var code = { "a": "z", "A": "Z", "b": "y", "B": "y", "c": "x", "C": "X", "d": "w", "D": "W", "e": "v", "E": "V", "f": "u", "F": "U", "g": "t", "G": "T", "h": "s", "H": "S", "i": "r", "I": "R", "j": "q", "J": "Q", "k": "p", "K": "P", "l": "o", "L": "O", "m": "n", "M": "N", "n": "m", "N": "M", "o": "l", "O": "L", "p": "k", "P": "K", "q": "j", "Q": "J", "r": "i", "R": "I", "s": "h", "S": "H", "t": "g", "T": "G", "u": "f", "U": "F", "v": "e", "V": "E", "w": "d", "W": "D", "x": "c", "X": "C", "y": "b", "Y": "B", "z": "a", "Z": "A", "ä": "ß", "Ä": "ẞ", "ö": "ü", "Ö": "Ü", "ü": "ö", "Ü": "Ö", "ß": "ä", "ẞ": "Ä" };
        return Array.from(string, c => code[c] || c).join('');
    }
    
    console.log(replace('Übermut2019')); // 'Öyvinfg2019'
    console.log(replace('Öyvinfg2019')); // 'Übermut2019'