How to convert Unicode Hex Characters to Latin-1 in JavaScript

Tags: , ,



I’m using rae-api to get the definition of the words in their dictionary. The problem is for example: I search for the definition of the word hola, it returns como salutación familiar.. I want to get the value of ó in Latin-1 characters: ó, therefore, the result would be como salutación familiar.

getHex function removes &#; and returns xF3 to the text. However, i want to convert all Unicode Hex characters to Latin-1.

I have tested a lot of answers in similar problems, but none of they works for me (example: decodeURIComponent or using Hex to utf8 libraries). I’m using Discord.js.

userInput is the word to search for

const { RAE } = require("rae-api");
const rae = new RAE();
        
//-----------------  RAE  -------------------------

    
function getHex(text) {
   text = text.replace(/&#(.*?);/g, function (a, b) {
        //Get the Latin-1 value of b and return it to the text
        return b;
   })

   return text;
}

rae.searchWord(`${userInput}`).then(r => {
    let wordID = r.getRes()[0].getId();

rae.fetchWord(wordID).then(word => {
    let defs = word.getDefinitions();
    let definition = defs[0].getDefinition();
        
    return message.channel.send(`La definición de ${userInput} es: ${getHex(definition)}`);
})
    
}).catch(e => { return message.channel.send("No se encontró esa palabra!")})
    

Answer

var input = 'F3';
var decimalValue = parseInt(input, 16); // Base 16 or hexadecimal
var character = String.fromCharCode(decimalValue);
console.log('Input:', input);
console.log('Decimal value:', decimalValue);
console.log('Character representation:', character);


Source: stackoverflow