I have a string called
"Pizza2Day!"
that I want to replace using a array set. In this array set I have the original alphabets as reference
var originalValues = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
and then I have the encryption key set
var encryptedValues = ['m', 'h', 't', 'f', 'g', 'k', 'b', 'p', 'j', 'w', 'e', 'r', 'q', 's', 'l', 'n', 'i', 'u', 'o', 'x', 'z', 'y', 'v', 'd', 'c', 'a'];
what I want to do is find any occurrences in the original string "Pizza2Day" of normal alphabets (a,b,c,d) and replace them with their substitutes in the encryption set (m,n,h,f). So the result would be "Njaam2Fmc!"
How would I go about doing this? Will a loop come in handy in this case?
Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.
The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
Another approach.
var dictionary = { "a": "m", "b": "h", "c": "t", "d": "f", "e": "g", "f": "k", "g": "b", "h": "p", "i": "j", "j": "w", "k": "e", "l": "r", "m": "q", "n": "s", "o": "l", "p": "n", "q": "i", "r": "u", "s": "o", "t": "x", "u": "z", "v": "y", "w": "v", "x": "d", "y": "c", "z": "a", "A": "M", "B": "H", "C": "T", "D": "F", "E": "G", "F": "K", "G": "B", "H": "P", "I": "J", "J": "W", "K": "E", "L": "R", "M": "Q", "N": "S", "O": "L", "P": "N", "Q": "I", "R": "U", "S": "O", "T": "X", "U": "Z", "V": "Y", "W": "V", "X": "D", "Y": "C", "Z": "A" },
string = "Pizza2Day!",
result = string.replace(/[a-z]/gi, m => dictionary[m]);
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With