Using regex to replace emotion character in javascript

I have JavaScript code.

var emoticons = { ':)': '<span class="emoticon emoticon_smile"></span>', ':-)': '<span class="emoticon emoticon_smile"></span>', ':(': '<span class="emoticon emoticon_sad"></span>', ':d': '<span class="emoticon emoticon_bigSmile"></span>', ':D': '<span class="emoticon emoticon_bigSmile"></span>' } 

and now, to replace emotion with a range in this text, I use the following functions

 function Emotions (text) { if (text == null || text == undefined || text == "") return; var pattern = /[:\-)(D/ pPy@ '*]+/gi; return text.replace(pattern, function (match) { return typeof emoticons[match] != 'undefined' ? emoticons[match] : match; }); } 

Now the above code works fine. If I pass the text to functions as below

 Emotions("Hey this is a test :( :("); 

see the space between the two symbols of emotions. But if I remove the space between the emotions, then it will not work. Below

 Emotions("Hey this is a test :(:("); 

Something is wrong in my regex, but I could not figure it out.

+6
source share
5 answers
 /:-?[()pPdD]/gi 

characters in [] brackets are posibilites and remain in order

+6
source

The expression cannot say that ":( :(" should be considered as two "blocks" because ":( :(" perfectly matches your regular expression pattern .

If you, for example, know that all of your emoticons start with a colon (:), you can use the following expression to check the "emoji" blocks

:[\-)(D/ pPy@ '*]+ (the colon is now in front of the character class)

+1
source

When you remove the space, your sequence of emotions :(:( matches your pattern /[:\-)(D/ pPy@ '*]+/ (as one sequence). Since there is no range associated with :(:( nothing returns.

You should find a way to delimit your character sequence (for example, adding space in front of your pattern, like this / [:\-)(D/ pPy@ '*]+/ , but don't forget to add space in front of your range in this case) .

0
source

try changing your regex to

var pattern = /:[\-)(D/ pPy@ '*]+/gi;

0
source

USe This Expresion Search and Your Code Will Work

var pattern = /: [(-) dD] + / gi;

0
source

Source: https://habr.com/ru/post/970838/


All Articles