Basically what I want to do is to match only strings that contain emojis and no other characters. It could have one or many emojis as long as there are no other characters.
I know there has been questions like it in the past but none of them supports all emojis.
I'm using the following to detect emojis but am unsure how to exclude other characters from it.
const regex = /\p{Extended_Pictographic}/ug
return regex.test(mystr);
These are my test cases and the expected results:
πΊπΈdπΈπ©πΌββ€οΈβπβπ©π½f -> false
t -> false
3 -> false
πΊπΈπΈπ©πΌ -> true
β€οΈ -> true
π -> true
π³ββοΈ -> true
π -> true
π -> true
You may test the result here: https://regex101.com/r/krwZ7W/1
Updated answer: The following is based on the below comment from Christopher (which they mention is itself based on a comment from outis).
Original comment from Christopher:
Based on the comment from @outis, here is a small fiddle which makes use of the regex and information from that answer. And the reference.
Feels like at the moment it is THE ultimate solution.
isEmojiOnly(str) {
const stringToTest = str.replace(/ /g,'');
const emojiRegex = /^(?:(?:\p{RI}\p{RI}|\p{Emoji}(?:\p{Emoji_Modifier}|\u{FE0F}\u{20E3}?|[\u{E0020}-\u{E007E}]+\u{E007F})?(?:\u{200D}\p{Emoji}(?:\p{Emoji_Modifier}|\u{FE0F}\u{20E3}?|[\u{E0020}-\u{E007E}]+\u{E007F})?)*)|[\u{1f900}-\u{1f9ff}\u{2600}-\u{26ff}\u{2700}-\u{27bf}])+$/u;
return emojiRegex.test(stringToTest) && Number.isNaN(Number(stringToTest));
}
Old Answer: The following fails for number emojis and flags and maybe more.
This is what I came up with, not sure how it holds up against all test cases but it should be decent enough to be usable. This function will test the input to see if it ONLY contains emojis.
function isEmojiOnly(str) {
// remove all white spaces from the input
const stringToTest = str.replace(/ /g,'');
const regexForEmojis = /\p{Extended_Pictographic}/ug;
const regexForAlphaNums = /[\p{L}\p{N}]+/ug;
// check to see if the string contains emojis
if (regexForEmojis.test(stringToTest)) {
// check to see if it contains any alphanumerics
if (regexForAlphaNums.test(stringToTest)) {
return false;
}
return true;
}
return false;
}