Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a string that contains complicated emojis?

Input:

Hello worldπŸ‘©β€πŸ¦°πŸ‘©β€πŸ‘©β€πŸ‘¦β€πŸ‘¦

Desired Output:

πŸ‘©β€πŸ‘©β€πŸ‘¦β€πŸ‘¦πŸ‘©β€πŸ¦°dlrow olleH

I tried several approaches but none gave me correct answer.

This failed miserablly:

const text = 'Hello worldπŸ‘©β€πŸ¦°πŸ‘©β€πŸ‘©β€πŸ‘¦β€πŸ‘¦';

const reversed = text.split('').reverse().join('');

console.log(reversed);

This kinda works but it breaks πŸ‘©β€πŸ‘©β€πŸ‘¦β€πŸ‘¦ into 4 different emojis:

const text = 'Hello worldπŸ‘©β€πŸ¦°πŸ‘©β€πŸ‘©β€πŸ‘¦β€πŸ‘¦';

const reversed = [...text].reverse().join('');

console.log(reversed);

I also tried every answer in this question but none of them works.

Is there a way to get the desired output?

like image 505
Hao Wu Avatar asked Oct 15 '22 02:10

Hao Wu


People also ask

How do I flip a character in a string?

Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0. The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).

How do you reverse a string in HTML?

innerHTML = String. prototype. reverse(s); after the element was loaded in page, so the value of s was empty (since it just loaded), and that function was never being called again to readjust the inner HTML of the p tag. Hope that can help.


1 Answers

If you're able to, use the _.split() function provided by lodash. From version 4.0 onwards, _.split() is capable of splitting unicode emojis.

Using the native .reverse().join('') to reverse the 'characters' should work just fine with emojis containing zero-width joiners

function reverse(txt) { return _.split(txt, '').reverse().join(''); }

const text = 'Hello worldπŸ‘©β€πŸ¦°πŸ‘©β€πŸ‘©β€πŸ‘¦β€πŸ‘¦';
console.log(reverse(text));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
like image 98
0stone0 Avatar answered Oct 16 '22 16:10

0stone0