4

我有一个用图像表情符号替换文字表情符号等的功能

我怎样才能使这个不区分大小写?我曾尝试在替换器中使用“gi”和“ig”,但似乎没有什么区别

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;
};
4

3 回答 3

2

改变:

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

到:

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

从此答案中获取的正则表达式转义函数转义字符串以用于 Javascript 正则表达式

于 2012-05-29T19:16:16.420 回答
1

这比表面上看起来要棘手一些。以下是一个完整的解决方案。为了简单和高效,它只对目标字符串使用一个正则表达式搜索。

请注意,因为它不区分大小写(例如,(hehe)(HeHe)被视为相同),:-d所以也被视为相同:-D

var emots = {
    ':)' : 'smile',
    ':-)' : 'smile'
    // Add the rest of your emoticons...
};

// Build the regex that will be used for searches
var emotSearch = [];
for (var p in emots) {
    if (emots.hasOwnProperty(p)) {
        emotSearch.push(p.replace(/[-[{()*+?.\\^$|]/g, '\\$&'));
        if (p !== p.toLowerCase()) {
            emots[p.toLowerCase()] = emots[p];
        }
    }
}
emotSearch = RegExp(emotSearch.join('|'), 'gi');

function smile(str) {
    return str.replace(emotSearch, function ($0) {
        var emot = $0.toLowerCase();
        if (emot in emots) {
            return '<img src="/emoticons/' + emots[emot] + '.gif" title="' + $0 + '" />';
        }
        return $0;
    });
}
于 2012-05-29T19:27:28.210 回答
-2

或者只是在运行检查之前在输入上使用 .toLowerCase() ?

于 2012-05-29T20:17:57.393 回答