Reputation: 1048
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
Upvotes: 43
Views: 107490
Reputation: 53598
If you have to work with strings that have, for whatever reason, literally the letters \u
followed by hexadecimals 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:
// put this in whatever utility library file you have:
export function convertUnicode(input) {
return input.replace(/\\+u([0-9a-fA-F]{4})/g, (a,b) =>
String.fromCharCode(parseInt(b, 16)));
}
And then in your component:
import { convertUnicode } from "...your util lib...";
function Hello(props) {
const name = convertUnicode(props.name);
return <div>Hello {name}</div>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Hello name="Informaci\\u00f3n"/>);
Fiddle: https://jsfiddle.net/shdye3pq/
Upvotes: 24
Reputation: 4893
Question title leads to this questions around React unicode issues, and sometimes simply this meta
tag is needed:
<html>
<head>
<meta charset="UTF-8">
</head>
</html>
Upvotes: 3
Reputation: 1228
To put the unicode write in your render()
and jsx, you can just:
<div>{'First \u00b7 Second'}</div>
, or
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
If doing this with libraries and other fonts, be sure that your font is imported first, make sure that you are using font-family: myFont
(i.e. "Font Awesome 5 Free"
). And make sure that the unicode that you are using is accurate.
Upvotes: 4
Reputation: 254926
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/
Upvotes: 56