Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Javascript displaying/decoding unicode characters

I have a string in unicode that i need to convert. I need to render the string with \u00f3 to ó. This is an example, it should happen with all other types of characters, á, í, ú...

I have the following basic code: https://jsfiddle.net/dddf7o70/

I need to convert

<Hello name="Informaci\u00f3n" /> 

into

Información 
like image 849
barracuda Avatar asked Feb 03 '16 01:02

barracuda


People also ask

What is ${} In react?

the ${} is the syntax for variables (or other code to be executed) inside template literals (`).

How convert JSON string to object in react native?

To convert JSON into an object, use theObject = JSON. parse(theString) . To convert an object into a JSON string, use theString = JSON. stringify(theObject) .


2 Answers

Just pass it as a JS string:

<Hello name={'Informaci\u00f3n'} /> 

No need to do any manual processing (which is error prone).

Fiddle: https://jsfiddle.net/dddf7o70/5/

like image 184
zerkms Avatar answered Sep 29 '22 09:09

zerkms


If you have to work with strings that have, for whatever reason, literally those \u.... codes in them instead of being real letters, convert them to numbers, and then use String.fromCharCode() to turn those numbers into real letters. We can use a regexp replace with handler function for this:

function convertUnicode(input) {   return input.replace(/\\u[0-9a-fA-F]{4}/g,function(a,b) {     var charcode = parseInt(b,16);     return String.fromCharCode(charcode);   }); }  var Hello = React.createClass({   getInitialState: function() {     return {       name: convertUnicode(this.props.name)     };   },   render: function() {     return <div>Hello {this.state.name}</div>;   } });  React.render(   <Hello name="Informaci\u00f3n" />,   document.getElementById('container') ); 

Fiddle: https://jsfiddle.net/cq7o4zgb/

like image 40
Mike 'Pomax' Kamermans Avatar answered Sep 29 '22 08:09

Mike 'Pomax' Kamermans