Javascript regex replace text with emoticons

后端 未结 3 1305
忘了有多久
忘了有多久 2021-01-07 11:40

I need to replace text like ;) or :p by emoticon but I can\'t create a regex in order to detect this. Now i can detect only like :wink:

3条回答
  •  一生所求
    2021-01-07 12:30

    This function takes a string and returns a string with all the replacements found inside of the emots object.

    function replaceText(text) {
      var emots = {
        ";)": "wink",
        ":)": "xxx",
        ":p": "xxx", 
      };
    
      for(var key in emots){
        if(emots.hasOwnProperty(key)){
          text = text.replace(new RegExp(escapeRegExp(key), 'g'), '');
        }
      }
      return text;
    }
    
    function escapeRegExp(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }
    

提交回复
热议问题