Created
February 4, 2018 12:49
-
-
Save geopic/dc0b12f88589957e308c41024db39ba4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// get string as argument | |
function switchCharCode(str) { | |
// split string | |
str = str.split(''); | |
str = str.map(function(char) { | |
let char_code; | |
if (char !== ' ') { | |
// convert each char to Unicode value and add three | |
char_code = char.charCodeAt(0); | |
char_code = char_code + 3; | |
if ((char_code >= 91 && char_code <= 96) || (char_code >= 123 && char_code <= 126)) { | |
// wrap around back to start of alphabet if char goes past 'Z' or 'z' | |
// Unicode values 91 to 96 / 123 to 126 represent non-alphabetic symbols | |
char_code = char_code - 26; | |
} else if (char_code >= 48 && char_code <= 64) { | |
// undo previous action if char is numeric (0-9) or belonging to a set of ASCII symbols | |
char_code = char_code - 3; | |
} | |
} else if (char == ' ') { | |
// char is whitespace, return whitespace Unicode value | |
char_code = 32; | |
} | |
// re-convert back to chars | |
char_code = char_code.toString(); | |
char_code = String.fromCharCode(char_code); | |
return char_code; | |
}) | |
// return new string | |
return str.join(''); | |
} | |
console.log(switchCharCode('Hello World')); // "Khoor Zruog" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment