简体   繁体   中英

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?

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

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