Faizan
Faizan

Reputation: 1898

Javascript Regex to match emoticon symbols in my array

I have this array that has emo symbols and associated image files for each emo path.

Working demo of my code on JSFIDDLE

But using this code, only :) this emo returns the correct smile.png image but rest of the emo are not working.

How do I write the correct regex that match each of these symbols and choose the appropriate file for each emo ?

 //Replace Emo with images
  function replaceEmoticons(text) {
  var emoticons = {
    ':)' : 'smile.png',
    ': )' : 'smile.png',
    ':D' : 'laugh.png',
    ':->' : 'laugh.png',
    ':d' : 'laugh-sm.png',
    ':-)': 'smile-simple.png',
    ':p': 'tounge.png',
    ':P': 'tounge-lg.png',
    ': P': 'tng1.png',
    '>-)': 'evil.png',
    ':(': 'sad.png',
    ':-(': 'sadd.png',
    ':-<': 'sadd.png',
    ':-O': 'surprise.png',
    ':O': 'sur2.png',
    ':o': 'sur3.png',
    ':-o': 'sur3.png',
    ':-*': 'kiss.png',
    ':*': 'kiss.png',
    ':-@': 'angry.png',
    ':@': 'angry.png',
    ':$': 'con2.png',
    ':-$': 'con1.png',
    'O.o': 'con2.png',
    'o.O': 'con2.png',
    ':/': 'weird.png',
    ':x': 'x.png',
    ':X': 'x.png',
    ':!': 's.png',
    '(:I': 'egg.png',
    '^.^': 'kit.png',
    '^_^': 'kit.png',
    ';)': 'wink.png',
    ';-)': 'wink.png',
    ":')": 'hc.png',
    ":'(": 'cry.png',
    "|-O": 'yawn.png',
    "-_-": 'poke.png',
    ":|": 'p1.png',
    "$_$": 'he.png'

  }, url = "images/emo/";
  // a simple regex to match the characters used in the emoticons
  return text.replace(/[:\-)D]+/g, function (match) {

    return typeof emoticons[match] != 'undefined' ?
           '<img class="emo" src="'+url+emoticons[match]+'"/>' :
           match;
  });
}


replaceEmoticons("Hi this is a test string :) with all :P emos working :D");

Upvotes: 3

Views: 1071

Answers (1)

Mark Reed
Mark Reed

Reputation: 95375

This regex:

 [:\-)D]+

Does not match many of the emoticons in your list. Any character other than :, \, -, ),or D will prevent it from being recognized.

If you have a list of strings you want to match, you can easily build a regex to match any of them (and nothing else) by escaping each one and joining them together with |. Something like this:

// given a string, return the source for a regular expression that will 
// match only that exact string, by escaping any regex metacharacters
// contained within.
RegExp.escape = function(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

// build a regex that will match all the emoticons. Written out, it looks
// like this:   /:\)|: \)|:D|:->|:d|:-\)|:p|:P|..../g
var emoticonRegex = 
  new RegExp(Object.keys(emoticons).map(RegExp.escape).join('|'), 'g');

Then use that in place of your literal regex:

return text.replace(emoticonRegex, function (match) { ...

Upvotes: 2

Related Questions