Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regular Expression to replace emotions character in javascript

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.

like image 301
Vimal Patel Avatar asked Jun 14 '14 14:06

Vimal Patel


People also ask

What does * do in regex?

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.

What is regular expression in JavaScript examples?

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.

How do you match a pattern in JavaScript?

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.


2 Answers

/:-?[()pPdD]/gi

characters in [] brackets are posibilites and remaining by order

like image 78
hparcalar Avatar answered Oct 22 '22 04:10

hparcalar


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)

like image 1
dlaxar Avatar answered Oct 22 '22 04:10

dlaxar