Stack Overflow Asked by user1199595 on December 7, 2021
How can I detect that the string only contains one emoji ? Now it returns true if it has any.
I want it only to be true if it contains only one emoji and nothing else.
function hasOneEmoji(str) {
const regEx = /(?:[u2700-u27bf]|(?:ud83c[udde6-uddff]){2}|[ud800-udbff][udc00-udfff])[ufe0eufe0f]?(?:[u0300-u036fufe20-ufe23u20d0-u20f0]|ud83c[udffb-udfff])?(?:u200d(?:[^ud800-udfff]|(?:ud83c[udde6-uddff]){2}|[ud800-udbff][udc00-udfff])[ufe0eufe0f]?(?:[u0300-u036fufe20-ufe23u20d0-u20f0]|ud83c[udffb-udfff])?)*/g;
if (str.match(regEx)) {
return true;
}
return false;
}
Assuming your regular expression is correctly matching emojis, then just add ^(?:...)$
around your literal so that's the only pattern allowed in the entire string:
function hasOneEmoji(str) {
return /^(?:(?:[u2700-u27bf]|(?:ud83c[udde6-uddff]){2}|[ud800-udbff][udc00-udfff])[ufe0eufe0f]?(?:[u0300-u036fufe20-ufe23u20d0-u20f0]|ud83c[udffb-udfff])?(?:u200d(?:[^ud800-udfff]|(?:ud83c[udde6-uddff]){2}|[ud800-udbff][udc00-udfff])[ufe0eufe0f]?(?:[u0300-u036fufe20-ufe23u20d0-u20f0]|ud83c[udffb-udfff])?)*)$/.test(str);
}
console.log(hasOneEmoji('?'));
console.log(hasOneEmoji('?Hello'));
console.log(hasOneEmoji('Hello?'));
console.log(hasOneEmoji('??'));
Answered by Patrick Roberts on December 7, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP