Szyfrator na stronie: kliknięcie

Praktyka: teksty i szyfry - JavaScript od podstaw: konsola (HTML/CSS/JS)

Model (`shiftChar`, `caesar`) przenosimy na stronę bez zmian, zmienia się tylko wejście i wyjście. Zamiast stałych w kodzie tekst i przesunięcie wpisuje użytkownik w formularzu, a wynik trafia do akapitu `#result`. Wartość pola to zawsze NAPIS (`.value`), dlatego przesunięcie zamieniamy na liczbę `Number(...)`: bez tego `+` skleiłby napisy zamiast dodać. Wynik wpisujemy przez `textContent`, więc nawet znaczniki HTML w tekście nie zostaną wykonane.

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>Szyfr Cezara</title>
  <style>
    body { font-family: sans-serif; max-width: 32em; }
    label { display: block; margin-top: 0.6em; }
    textarea, input { font: inherit; padding: 0.3em; }
    textarea { width: 100%; height: 4em; }
    button { font: inherit; margin-top: 0.6em; padding: 0.3em 0.8em; }
    #result { font-family: monospace; font-size: 1.2em; background: #eef2ff; padding: 0.5em; min-height: 1.2em; }
    .error { color: #b91c1c; }
  </style>
</head>
<body>
  <h1>Szyfr Cezara</h1>
  <label>Tekst: <textarea id="text"></textarea></label>
  <label>Przesunięcie: <input id="shift" type="number" value="3"></label>
  <button id="encode">Szyfruj</button>
  <p id="result"></p>
  <script>
    function shiftChar(ch, k) {
      const code = ch.charCodeAt(0);
      if (code >= 65 && code <= 90) {
        return String.fromCharCode(((code - 65 + k) % 26 + 26) % 26 + 65);
      }
      if (code >= 97 && code <= 122) {
        return String.fromCharCode(((code - 97 + k) % 26 + 26) % 26 + 97);
      }
      return ch;
    }

    function caesar(text, k) {
      let result = '';
      for (const ch of text) {
        result += shiftChar(ch, k);
      }
      return result;
    }
    const textField = document.getElementById('text');
    const shiftField = document.getElementById('shift');
    const result = document.getElementById('result');

    document.getElementById('encode').addEventListener('click', () => {
      const k = Number(shiftField.value);
      result.textContent = caesar(textField.value, k);
    });
  </script>
</body>
</html>

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu JavaScript od podstaw: konsola·Zaloguj się, aby zapisać postęp na koncie.