I have following 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 the emotion with span in the given text I am using 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 is working fine.If I pass the text in the function as below
Emotions("Hey this is a test :( :(");
see the space between 2 emotions character. But if I remove the space between both the emotion then it does not work.Like below
Emotions("Hey this is a test :(:(");
There is something wrong with my regular expression but I am not been able to figure it out.
The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.
A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern.
RegExp Object A regular expression is a pattern of characters. The pattern is used to do pattern-matching "search-and-replace" functions on text. In JavaScript, a RegExp Object is a pattern with Properties and Methods.
/:-?[()pPdD]/gi
characters in [] brackets are posibilites and remaining by order
The expression cannot tell that ":(:(" should be treated as two "blocks" since ":(:(" perfectly satisfies your regex pattern
.
If you, for example, know that all your emojis start with a colon (:) you could use the following expression to check for emoji "blocks"
:[\-)(D/pPy@'*]+
(the colon is now in front of the character-class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With