Javascript regex replace text with emoticons

后端 未结 3 1308
忘了有多久
忘了有多久 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:24

    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 '';
                        } else {
                    return match;
                        }
                    });
        }
    
        return result;    
    }
    

提交回复
热议问题