Its a trap
Its a trap

Reputation: 3

Changing Unicode symbols (") to the equivalent html symbol (")

I am working on a project in react (JavaScript, html) where we make a call to a google search api that returns a title with the content of the search result. currently when we get the results back they are in Unicode for example

this isn't what I want

what I would like is for it to be

 this isn't what i want

I would do a string.replace however there are multiple different codes and I can't account for them all without it being lengthy. any suggestions on how I can change this?

Upvotes: 0

Views: 534

Answers (1)

over-engineer
over-engineer

Reputation: 1053

You can simply create an element, set its HTML content as your encoded string, and then get back its text content.

const encodedResults = 'this isn't what I want';
const div = document.createElement('div');
div.innerHTML = encodedResults;
const decodedResults = div.textContent; // this isn't what i want

Edit: @Mr Lister mentioned that the above method works only when the input doesn't contain actual html tags.

For inputs containing html tags, you can create a textarea, set its content, and then get back its value.

const encodedResults = 'this <i>isn&#39;t</i> what I want';
const textarea = document.createElement('textarea');
textarea.innerHTML = encodedResults;
const decodedResults = textarea.value; // this <i>isn't</i> what i want

Upvotes: 3

Related Questions