'encrypt alphabet to unicode does not work
This is project from freecodecamp where a string is encrypt by the values of the letters are shifted by 13 places All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on. i test numadd by regex numadd is either equal to num+13 or numadd-26. some letter went wrong and do not return an uppercase letter please someone explain whats wrong
function rot13(str) {
var str2 = '';
var arr1 = []
var arr2 = []
var reg = /[^A-Z]/
// var char
if (str.includes(' ') == false) {
for (let i = 0; i < str.length; i++) {
var char = '';
var numres
let num = str.charCodeAt(i)
// console.log(num)
// var numadd = num + 13;
// if num+13 not uppercase
if (reg.test(num + 13)) {
numres = num - 13
}
// if num+13 is uppercase
else {
numres = num + 13
}
char = String.fromCharCode(numres)
str2 += char
}
console.log(str2);
}
}
rot13("SERRPBQRPNZC");
Solution 1:[1]
reg.test(num + 13)
checks the textual representation of the number num + 13
(applying implicit type conversion) so it always says True (do not match an uppercase letter) and always is computed numres = num - 13
.
Use reg.test(String.fromCharCode(num + 13))
instead as follows:
function rot13(str) {
var str2 = '';
var arr1 = []
var arr2 = []
var reg = /[^A-Z]/
// var char
if (str.includes(' ') == false) {
for (let i = 0; i < str.length; i++) {
var char = '';
var numres
let num = str.charCodeAt(i)
// console.log(num)
// var numadd = num + 13;
// if num+13 not uppercase
// ???????????????????
if (reg.test(String.fromCharCode(num + 13))) {
numres = num - 13
}
// if num+13 is uppercase
else {
numres = num + 13
}
char = String.fromCharCode(numres)
str2 += char
}
console.log(str2);
}
}
rot13("SERRPBQRPNZC");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | JosefZ |