简体   繁体   English

Javascript正则表达式用表情符号替换文本

[英]Javascript regex replace text with emoticons

I need to replace text like ;) or :p by emoticon but I can't create a regex in order to detect this. 我需要通过表情符号来替换像;):p这样的文本,但我无法创建正则表达式来检测它。 Now i can detect only like :wink: 现在我只能检测到:wink:

function replaceEmoticons(text) {
  var emots = {
    ";)": "wink",
    ":)": "xxx",
    ":p": "xxx", 

  };

  return text.replace(/:(.*?):/g, function (match) {
    return typeof emots[match] != 'undefined' ?
           '<img src="http://localhost:8080/'+emots[match]+'.png"/>' :
           match;
  });
}

What is the good regex for that ? 那个好的正则表达式是什么?

Try the following.However, you should escape the special characters ( and ) in your smileys when making the regexes. 请尝试以下操作。但是,在制作正则表达式时,您应该在表情符号中转义特殊字符(和)。

//helper function to escape special characters in regex //帮助函数来转义正则表达式中的特殊字符

function RegExpEscape(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 
}

function replaceEmoticons(text) {   
    var emoticons = {
        ':)'         : 'smile.gif',
        ':('         : 'sad.gif',
        ';)'         : 'wink.gif'


    }

    var result = text;
    var emotcode;
    var regex;

    for (emotcode in emoticons)
    {
        regex = new RegExp(RegExpEscape(emotcode), 'gi');
        result = result.replace(regex, function(match) {
            var pic = emots[match.toLowerCase()];

            if (pic != undefined) {
                return '<img src="' + pic + '"/>';
                    } else {
                return match;
                    }
                });
    }

    return result;    
}

This function takes a string and returns a string with all the replacements found inside of the emots object. 此函数接受一个字符串并返回一个字符串,其中包含在emots对象中找到的所有替换。

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'), '<img src="http://localhost:8080/' + emots[key] + '.png"/>');
    }
  }
  return text;
}

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

I modified AK1's answer and provided an example. 我修改了AK1的答案并提供了一个例子。

 // Official Twitch robot emotes: https://twitchemotes.com var emoticons = { ':)' : 'ebf60cd72f7aa600', ':(' : 'd570c4b3b8d8fc4d', ':o' : 'ae4e17f5b9624e2f', ':z' : 'b9cbb6884788aa62', 'B)' : '2cde79cfe74c6169', ':\\\\' : '374120835234cb29', ';)' : '3407bf911ad2fd4a', ';p' : '3407bf911ad2fd4a', ':p' : 'e838e5e34d9f240c', 'R)' : '0536d670860bf733', 'o_O' : '8e128fa8dc1de29c', ':D' : '9f2ac5d4b53913d7', '>(' : 'd31223e81104544a', '<3' : '577ade91d46d7edc' } // Convert the emoticon map entries into their fully-qualified paths. mapIdsToPaths(emoticons, 'https://static-cdn.jtvnw.net/jtv_user_pictures/', 'chansub-global-emoticon-', '24x18'); // Replace all possible emotes in each paragraph. document.querySelectorAll('p').forEach(e => e.innerHTML = replaceEmoticons(e.innerHTML, emoticons)); function replaceEmoticons(text, emotes) { return Object.keys(emotes).reduce((result, emote) => { return result.replace(new RegExp(RegExpEscape(emote), 'gi'), function(match) { return (img => img != null ? '<img src="' + img + '"/>' : match)(emotes[match]); }); }, text); } // helper function to escape special characters in regex function RegExpEscape(text) { return text.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&"); } // Map emote ids to their URLs. function mapIdsToPaths(emotes, url, prefix, size) { Object.keys(emotes).forEach((id) => { emotes[id] = url + prefix + emotes[id] + '-' + size + '.png'; }); } 
 <p>Hello ;)<p> <p>How are you :)?<p> <p>o_O Today was not a good day... :(<p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM