Search code examples
javascriptjqueryreplacecase-insensitive

Make replace function case-insensitive


I have a function that replaces text smilies etc. with image emoticons

How can I make this case-INsensitive? I have tried using "gi" and "ig" at the replacer, but it does'nt seem to make a difference

var emots = {
    ':)' : 'smile',
    ':-)' : 'smile',
    ';)' : 'wink',
    ';-)' : 'wink',
    ':(' : 'downer',
    ':-(' : 'downer',
    ':D' : 'happy',
    ':-D' : 'happy',
    '(smoke)' : 'smoke',
    '(y)' : 'thumbsup',
    '(b)' : 'beer',
    '(c)' : 'coffee',
    '(cool)' : 'cool',
    '(hehe)' : 'tooth',
    '(haha)' : 'tooth',
    '(lol)' : 'tooth',
    '(pacman)' : 'pacman',
    '(hmm)' : 'sarcastic',
    '(woot)' : 'woot',
    '(pirate)' : 'pirate',
    '(wtf)' : 'wtf'
};

function smile(str){
    var out = str;
        for(k in emots){
            out = out.replace(k,'<img src="/emoticons/'+emots[k]+'.gif" title="'+k+'" />','g');
        }
    return out;
};

Solution

  • Change:

    out = out.replace(k,'<img src="/emoticons/'+emots[k]+'.gif" title="'+k+'" />','g');
    

    To:

    out = out.replace(new RegExp(k.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), 'ig'), '<img src="/emoticons/'+emots[k]+'.gif" title="'+k+'" />');
    

    Regex escaping function taken from this answer Escape string for use in Javascript regex