Vinicius Morais
Vinicius Morais

Reputation: 595

How convert these characters?

I'm making a App in React that receive a specific html page and transform into a page in React, but when a put some string in a <Text> these characters are not converting:

enter image description here

The representation of &#8212; is .

What these characters are called? Is there a way in React to convert these characters into their corresponding text?

Upvotes: 4

Views: 1538

Answers (1)

Hend El-Sahli
Hend El-Sahli

Reputation: 6742

These symbols are called HTML Symbol Entities Many mathematical, technical, and currency symbols, are not present on a normal keyboard.

If no entity name exists, you can use an entity number, a decimal, or hexadecimal reference.

A Fast workaround for a single html entity that you know:

    <Text>
      {yourText.replace(/&#8212;/gi, '-')}
    </Text>

You could use this npm module to decode text before rendering:

Example for multiple html entities

const re = /&[^\s]*;/gi;
const allHtmlEntities = [];
while ((match = re.exec(youtText)) != null) {
  const htmlEntity = yourText.substring(match.index, 7);
  if (allHtmlEntities.indexOf(htmlEntity) === -1) {
    allHtmlEntities.push(htmlEntity);
  }
}

const entities = new Entities();

for (let i = 0; i < allHtmlEntities.length; i++) {
  const decodedValue = entities.decode(allHtmlEntities[i]);
  yourText = yourText.replace(new RegExp(allHtmlEntities[i], 'g'), decodedValue);
}

Upvotes: 2

Related Questions