-2

I was having problem with my encoder, since it is not working as I expected.
The variable "message" declared throught a input added in my html page

var ENCODE_OPC = ['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', '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', '1', '2', '3', '4', '5', '6','7','8', '9', '0', ' '];
var DECODE_OPC = ['&2p', '&4g', '&6g', '&7b', '&4v', '&8n', '&4b', '&1d', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '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', '1', '2', '3', '4', '5', '6','7','8', '9', '0', ' '];
for (var q = 0; q < 63; q++) {
    message.replace(ENCODE_OPC[q], DECODE_OPC[q]);
}
console.log(message);

2 Answers2

2

Two problems:

  1. message.replace() doesn't modify the string in place, it returns a new string. You need to assign the result back to the variable: message = message.replace(...);
  2. When the first argument to replace() is a string, it only replaces the first match. You need to use a regular expression with the g flag to replace all matches.
for (var q = 0; q < ENCODE_OPC.length; q++) {
    message = message.replace(new RegExp(ENCODE_OPC[q], 'g'), DECODE_OPC[q]);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Try this code

var ENCODE_OPC = ['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', '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', '1', '2', '3', '4', '5', '6','7','8', '9', '0', ' '];
var DECODE_OPC = ['&2p', '&4g', '&6g', '&7b', '&4v', '&8n', '&4b', '&1d', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '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', '1', '2', '3', '4', '5', '6','7','8', '9', '0', ' '];
var encoded = '';
var message = "Hello world";
for (var q = 0; q < message.length; q++) {
    encoded += DECODE_OPC[ENCODE_OPC.indexOf(message[q])];
}
console.log(message, encoded);

Output

Hello world H&4vllo worl&7b
Aqib Mukhtar
  • 361
  • 1
  • 5