2012-05-29 23 views
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; 
}; 
+0

「我」只能在firefox中工作,因爲我看到它 – mowgli

回答

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+'" />'); 

從這個答案中取出正則表達式轉義函數Escape string for use in Javascript regex

+0

那裏面(k在emots){)? – mowgli

+0

@mowgli是的,沒錯。它只是從你的替換函數中取出標誌並將它們轉換爲正則表達式的標誌。 'escapeRegExp'轉義所有特殊的正則表達式字符,儘管你只需要用你的輸入來轉義'('和')'',最好是在你添加新的表情符號時使用':]'或其他字符上。 – Paulpro

+0

好吧;)但我想...在循環內創建一個函數是不是錯了?它會被創建(或檢查,而不是重新創建,我不知道)每個字母我猜 – mowgli

1

這比它有點棘手錶面上的ppears。以下是完整的解決方案。爲了簡單和高效,它只對目標字符串使用一次正則表達式搜索。

注意,因爲它是不區分大小寫(例如,(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; 
    }); 
} 
+0

哇很多代碼..沒有嘗試過。另一個較短的答案是完美的。簡單就好;) – mowgli

+0

就這樣吧。儘管如此,您知道,您提到的另一個答案需要對emot的每個屬性單獨進行搜索和替換,這會顯着降低效率,並且會隨着添加更多表情符號來搜索而變得更慢。它還使用不必要的詳細正則表達式來轉義正則表達式元字符。 – slevithan

-2

或者只是在輸入之前使用.toLowerCase()運行檢查之前?