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

これは、表面に表示されるよりも少し注意が必要です。以下は完全なソリューションです。単純さと効率のために、ターゲット文字列に対して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 に答える