faqts : Computers : Programming : Languages : JavaScript : Language Core : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

59 of 77 people (77%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How can I ROT13 encode/decode a string?

Jan 10th, 2001 10:25
Martin Honnen,


The following JavaScript 1.2 code does that:
function rot13 (string) {
  var aCode = 'a'.charCodeAt();
  var zCode = 'z'.charCodeAt();
  var ACode = 'A'.charCodeAt();
  var ZCode = 'Z'.charCodeAt();
  var result = '';
  for (var c = 0; c < string.length; c++) {
    var charCode = string.charCodeAt(c);
    if (charCode >= aCode && charCode <= zCode)
      charCode = aCode + (charCode - aCode + 13) % 26;
    else if (charCode >= ACode && charCode <= ZCode)
      charCode = ACode + (charCode - ACode + 13) % 26;
    result += String.fromCharCode(charCode);
  }
  return result;
}
//Example
alert(rot13('Kibology'));
alert(rot13(rot13('Kibology'));