0

I have a string in JavaScript like so:

var string = " Hello  world!"; // Length of emoji at end: 2 characters ("".length = 2)

Or:

var string = " Hello world! ‍‍"; // Length of emoji at end: 8 characters ("‍‍".length = 8)

Or a string without an emoji:

var string = " Hello world!"; // No emoji at end

I need to find the out following:

  1. Is there an emoji at the end of the string?
  2. How many characters does it consist of?

I came as far as detecting two-character emojis with the following code:

var emoji = new RegExp('\\p{Extended_Pictographic}', 'u');
var isEmoji = emoji.test(string.slice(-2)); // true for the first string

However, this obviously does not detect the length (e.g. ‍‍ = 8). If anyone has experience with emojis in JavaScript and could point me in the right direction it would be very much appreciated.

Ood
  • 1,445
  • 4
  • 23
  • 43
  • Does this answer your question? [How to count the correct length of a string with emojis in javascript?](https://stackoverflow.com/questions/54369513/how-to-count-the-correct-length-of-a-string-with-emojis-in-javascript) – Peter B Oct 19 '22 at 23:28
  • @PeterB Thank you, but in this case there is another step involved. I need to find out the length *at the end* without knowing what comes before it, or the length of the preceding content. A simple '.length' will unfortunately not do the trick in my case. – Ood Oct 19 '22 at 23:33

1 Answers1

1

The rule is that every emoji that consists of several unicode characters is simply a combination of several emojis, so if you divide the entire string into an array by using the spread operator, then if the last element was an emoji, no matter what its length... then now the last element in the array must also be Emoji

var string1 = " Hello world! ‍‍";
var string2 = " Hello world! ‍‍!";
var string3 = " Hello  world!";
var string4 = " Hello  world!!";
var emoji = new RegExp('\\p{Extended_Pictographic}', 'u');
var isEmoji1 = emoji.test([...string1].at(-1)); 
var isEmoji2 = emoji.test([...string2].at(-1)); 
var isEmoji3 = emoji.test([...string3].at(-1)); 
var isEmoji4 = emoji.test([...string4].at(-1)); 

console.log(isEmoji1)
console.log(isEmoji2)
console.log(isEmoji3)
console.log(isEmoji4)
Haim Abeles
  • 982
  • 6
  • 19
  • Thank you for the answer. This certainly does work to detect longer emojis like ‍‍. However, I also need to detect after how many characters starting from the end that emoji ends, e.g. if it ends with = 2, for ‍‍ = 8. – Ood Oct 19 '22 at 23:40