React Javascript displaying / decoding Unicode characters

I have a Unicode string that I need to convert. I need to display a line from \ u00f3 to -. This is an example, this should happen with all other types of characters: รก, รญ, รบ ...

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

I need to convert

<Hello name="Informaci\u00f3n" /> 

in

 Informaciรณn 
+17
source share
4 answers

If you need to work with strings that for some reason contain these \u.... codes \u.... instead of real letters, convert them to numbers and then use String.fromCharCode () to turn these numbers into real letters, We can use regular expression replace with handler function for this:

 function convertUnicode(input) { return input.replace(/\\u(\w\w\w\w)/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') ); 

Violin: https://jsfiddle.net/dddf7o70/4/

+15
source

Just pass it as a JS string:

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

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

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

+24
source

React automatically converts Unicode using the dangerouslySetInnerHTML attribute.

See for more information: https://reactjs.org/docs/dom-elements.html

 export default class Hello extends Component { render() { return ( <div> <div dangerouslySetInnerHTML={{ __html: this.props.name}}></div> </div> ); } } 
+7
source

To add a Unicode entry to your render() and jsx , you can simply:

 <div>{'First \u00b7 Second'}</div> 

or

 <div>{'First ' + String.fromCharCode(183) + ' Second'}</div> 

If you do this with libraries and other fonts, make sure your font is imported first, make sure you use font-family: myFont (ie "Font Awesome 5 Free" ). And make sure the unicode you are using is accurate.

0
source

Source: https://habr.com/ru/post/1242142/


All Articles