Replace a list of emoticons with their images

前端 未结 3 961
挽巷
挽巷 2020-11-27 14:31

I have an array with:

emoticons = {
   \':-)\' : \'smile1.gif\',
   \':)\'  : \'smile2.gif\',
   \':D\'  : \'smile3.gif\'     
}

then i hav

相关标签:
3条回答
  • 2020-11-27 15:14

    Another approach:

    function replaceEmoticons(text) {
      var emoticons = {
        ':-)' : 'smile1.gif',
        ':)'  : 'smile2.gif',
        ':D'  : 'smile3.gif'
      }, url = "http://www.domain.com/";
      // a simple regex to match the characters used in the emoticons
      return text.replace(/[:\-)D]+/g, function (match) {
        return typeof emoticons[match] != 'undefined' ?
               '<img src="'+url+emoticons[match]+'"/>' :
               match;
      });
    }
    
    replaceEmoticons('this is a simple test :)');
    // "this is a simple test <img src="http://www.domain.com/smile2.gif"/>"
    

    Edit: @pepkin88 made a really good suggestion, build the regular expression based on the property names of the emoticons object.

    It can be easily done, but we have to escape meta-characters if we want this to work properly.

    The escaped patterns are stored on an array, that is later used to build the regular expression using the RegExp constructor, by basically joining all the patterns separated with the | metacharacter.

    function replaceEmoticons(text) {
      var emoticons = {
        ':-)' : 'smile1.gif',
        ':)'  : 'smile2.gif',
        ':D'  : 'smile3.gif',
        ':-|'  : 'smile4.gif'
      }, url = "http://www.domain.com/", patterns = [],
         metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;
    
      // build a regex pattern for each defined property
      for (var i in emoticons) {
        if (emoticons.hasOwnProperty(i)){ // escape metacharacters
          patterns.push('('+i.replace(metachars, "\\$&")+')');
        }
      }
    
      // build the regular expression and replace
      return text.replace(new RegExp(patterns.join('|'),'g'), function (match) {
        return typeof emoticons[match] != 'undefined' ?
               '<img src="'+url+emoticons[match]+'"/>' :
               match;
      });
    }
    
    replaceEmoticons('this is a simple test :-) :-| :D :)');
    
    0 讨论(0)
  • 2020-11-27 15:18
    for ( smile in emoticons )
    {
       text = text.replace(smile, '<img src="' + url + emoticons[smile] + '" />');
    }
    
    0 讨论(0)
  • 2020-11-27 15:21

    Using a regex with an array of find replace elements works well.

    var emotes = [
        [':\\\)', 'happy.png'],
        [':\\\(', 'sad.png']
    ];
    
    function applyEmotesFormat(body){
        for(var i = 0; i < emotes.length; i++){
            body = body.replace(new RegExp(emotes[i][0], 'gi'), '<img src="emotes/' + emotes[i][1] + '">');
        }
        return body;
    }
    
    0 讨论(0)
提交回复
热议问题