简体   繁体   English

使替换功能不区分大小写

[英]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 我试过在替换器上使用“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;
};

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 正则表达式转义函数取自此答案Escape字符串用于Javascript正则表达式

This is a bit trickier than it appears on the surface. 这比表面上看起来有点棘手。 Following is a complete solution. 以下是完整的解决方案。 It uses only one regex search on the target string, for simplicity and efficiency. 它仅对目标字符串使用一次正则表达式搜索,以简化和提高效率。

Note that, because it's case insensitive (eg, (hehe) and (HeHe) are treated the same), :-d is also treated the same as :-D . 请注意,因为它不区分大小写(例如, (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;
    });
}

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

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

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