Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON parse emoji unicode crashing my react native project

Tags:

Whenever I try to display some data fetched in my React Native project from my API endpoint I get this JSON parse error: JSON parse error on line 0 near .."}], [18933, "RC': expected another Unicode escape for the second half of surrogate pair

Clearly, there is a missing escape character for Unicode escape symbol.

My string is "You can try, but I don’t think so πŸ˜‚πŸ˜‚"

I tried printing the string in the console and it displays fine, but when I try to display it in React Native's <Text></Text> component my app crashes.

Any guidance would be appreciated.

like image 269
Eugene Yakovlev Avatar asked Jun 27 '19 21:06

Eugene Yakovlev


1 Answers

UPDATE

I found that the problem was with the JavaScript String.substring() method. It does not know how to properly split unicode surrogate pairs and therefore will try to split the string in the middle of a pair if you're unlucky with the positioning.

I solved the problem by using a library called "runes" that properly splits and takes a substring of a string with unicode surrogate pairs honored.

Problem: postComment.substring(0, 35) Solution: runes.substr(postComment, 0, 35)

Simply install the runes library and use runes.substr(yourString, start, end) to handle unicode surrogate pairs in your string :)

like image 101
Eugene Yakovlev Avatar answered Oct 05 '22 11:10

Eugene Yakovlev