Regex matching list of emoticons of various type

拟墨画扇 提交于 2019-12-06 15:21:35

I'm pretty sure you don't need the funny stuff you do at the beginning of each for loop to modify the regex. Get rid of that, and there's nothing stopping you from merging the two sets together.

However, you should escape the special characters ( and ) in your smileys when making the regexes. Also, I would suggest making the regex search case-insensitive so that <dog> and <DOG> are both matched.

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

function replaceEmoticons(text) {   
    var emots = {
        ':)'         : 'smile.gif',
        ':('         : 'sad.gif',
        '&lt;dog&gt;': 'dog.gif',
        '&lt;fly&gt;': 'fly.gif'
    }

    var result = text;
    var emotcode;
    var regex;

    for (emotcode in emots)
    {
        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;    
}

use |

you could do something like:

re = new RegExp(smiley1|smiley2|...|smileyN);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!