Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

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

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!")})
    

question from:https://stackoverflow.com/questions/65872048/how-to-convert-unicode-hex-characters-to-latin-1-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...