Skip to content

Instantly share code, notes, and snippets.

@moon-goon
Last active January 28, 2016 19:08
Show Gist options
  • Save moon-goon/2e7651838c9ad911c26b to your computer and use it in GitHub Desktop.
Save moon-goon/2e7651838c9ad911c26b to your computer and use it in GitHub Desktop.
Javascript / Encode and Decode using customized Regex
var encode = "abcdefg !@#$%^&*()"
var decode = "zyxwvut";
var swapValue = {
a:"z",
b:"y",
c:"x",
d:"w",
e:"v",
f:"u",
g:"t",
h:"s",
i:"r",
j:"q",
k:"p",
l:"o",
m:"n",
n:"m",
o:"l",
p:"k",
q:"j",
r:"i",
s:"h",
t:"g",
u:"f",
v:"e",
w:"d",
x:"c",
y:"b",
z:"a"
};
// cunstructed custom regular expression object with global modifier (all matches) and insensitive(case) modifier
// swap value with join method (a - > z)
var regEncode = new RegExp(Object.keys(swapValue).join("|"),"gi");
encode = encode.replace(regEncode, function(matched){
return swapValue[matched.toLowerCase()];
});
var result = encode.replace(/[^a-zA-Z 0-9\s]+/g,'');
console.log(result);
/*
decode = decode.replace(regEncode, function(matched){
return swapValue[matched.toLowerCase()];
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment