简体   繁体   中英

javascript unicode connection with html

I have a program that converts binary/morse/hex to ASCII but for some reason the output to the dom shows squares. I'm assuming it's because it doesn't know how to interpret the characters.

I don't know how to get javascript to show the right characters. In the console it gives the correct response but as soon as I send it to the DOM it shows those dreaded boxes.

Firstly I would like to know why the console is showing the correct output but the DOM doesn't, and secondly how to I get the DOM to show the correct output.

I tried changing the HTML encoding to UTF-16 but that didn't work. I'm using chrome. here is a small piece of the program

 if (baseButton.textContent == "morse") { const get = await fetch("morse.json") //this gets the morse from a JSON file const morseData = await get.json() const keys = Object.keys(morseData); const values = Object.values(morseData); let morseArray = secretMessage.split(' ') // this is the morse/binary/hex... from an input in html let string = '' for (let i = 0; i < morseArray.length; i++) { for (let j = 0; j < keys.length; j++) { if (morseArray[i] == values[j]) string += keys[j] } } console.log(string) //this gives the correct output in the console output.textContent = string.replace(/ /g, " ") // this shows boxes in the DOM } // output is displayed in the HTML below
 <div id="result"> <span>result:</span> <p> <pre id="code"></pre> </p> </div>

I cannot tell from the code you show - we need to see your object, The binary likely isn't stringified

But for morse this is simpler - I used _ as space

 const secretMessage = ".... . .-.. .-.. --- _.-- ---.-. .-.. -.."; const a2morse = {"_": "_", "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":"--.."}; const morse2a = Object.keys(a2morse).reduce((acc,cur) => { acc[a2morse[cur]] = cur return acc },{}) let str = secretMessage.split(" ").map(l => `${morse2a[l]}`).join("") console.log(str) //this gives the correct output in the console document.getElementById('output').textContent = str
 <pre id="output"></pre>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM