Skip to content Skip to sidebar Skip to footer

Obfuscate Text Using Javascript?

I'm looking to obfuscate (to make obscure, unclear, or unintelligible) paragraph text. Essentially I need to be able to control where it starts and stops. I don't want people pre

Solution 1:

You can make a reasonable attempt at this using vanilla JavaScript, while noting the concerns in the comments of course, particularly the point that if the original text is sent to the client it will of course be available to them.

let inputText = `“It Will Feed my Revenge!” To bait fish withal: if it will feed nothing else, it will feed my revenge. He hath disgraced me, and hindered me half a million; laughed at my losses, mocked at my gains, scorned my nation, thwarted my bargains, cooled my friends, heated mine enemies; and what's his reason?`;

functiongetRandomChar() {
   const characters = 'abcdefghijklmnopqrstuvwxyz';
   return characters.charAt(Math.floor(Math.random() * characters.length));
}

functiongetReplacement(char) {
  if (/^[^a-z]+$/i.test(char)) {
      return char;
  }
  let replacement = getRandomChar();
  if (char.toUpperCase() === char) {
      replacement = replacement.toUpperCase();
  }
  return replacement;
}

functionobfuscate(text, start = 0, end) {
    end = end || text.length;
    const obfuscatedSection = Array.prototype.map.call(text.substring(start,end), getReplacement).join("");
    return text.substring(0, start) + obfuscatedSection + text.substring(end);
}

console.log("Original text:", inputText);
console.log("\nObfuscated text:", obfuscate(inputText, 15, 200));

Post a Comment for "Obfuscate Text Using Javascript?"