首页 > 解决方案 > 如何使用 javascript 将 textarea 转换为显示其他内容(例如 base64 解密)?

问题描述

我正在尝试在 HTML 中创建一个解密页面。我可以获得输入,并将其显示为输出,但我对如何更改中间的文本感到困惑。到目前为止,这是我的代码:http: //jsfiddle.net/RZwmX/1

HTML:

<textarea name="CipherText" id="CipherText" placeholder="Enter ciphertext here:"></textarea>
<div id="prevCom"></div>

Javascript:

wpcomment.onkeyup = wpcomment.onkeypress = function(){
        wpcomment=btoa(wpcomment);
    document.getElementById('prevCom').innerHTML = this.value;
}

//////////////////////////////////////
//from: https://scotch.io/tutorials/how-to-encode-and-decode-strings-with-base64-in-javascript
// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

我从https://scotch.io/tutorials/how-to-encode-and-decode-strings-with-base64-in-javascript获取代码。Base64 只是一个例子。我想知道的是如何进行过渡。在我的第 3 行 javascript 的 JSFiddle 中,我想到了如何实现转换,但这不起作用。

标签: javascripthtmlencryptionbase64

解决方案


我会做这样的事情:

const input = document.querySelector('#encoded-input')
const output = document.querySelector('#decoded-output')

input.oninput = e => {
  try {
    output.innerText = atob(e.target.value)
  } catch (error) {
    output.innerText = e.target.value
      ? 'Please enter a valid Base64 encoded value.'
      : ''
  }
}
<textarea id="encoded-input"></textarea>
<div id="decoded-output"></div>


推荐阅读