2016-02-28 69 views
3

我有這個數組,每個emo路徑都有emo符號和相關的圖像文件。Javascript正則表達式來匹配我的數組中的表情符號

Working demo of my code on JSFIDDLE

但是使用這個代碼,只有:)這EMO返回正確的smile.png形象,但情緒的休息不工作。

如何編寫符合每個符號的正確正則表達式併爲每個emo選擇適當的文件?

//Replace Emo with images 
    function replaceEmoticons(text) { 
    var emoticons = { 
    ':)' : 'smile.png', 
    ':)' : 'smile.png', 
    ':D' : 'laugh.png', 
    ':->' : 'laugh.png', 
    ':d' : 'laugh-sm.png', 
    ':-)': 'smile-simple.png', 
    ':p': 'tounge.png', 
    ':P': 'tounge-lg.png', 
    ': P': 'tng1.png', 
    '>-)': 'evil.png', 
    ':(': 'sad.png', 
    ':-(': 'sadd.png', 
    ':-<': 'sadd.png', 
    ':-O': 'surprise.png', 
    ':O': 'sur2.png', 
    ':o': 'sur3.png', 
    ':-o': 'sur3.png', 
    ':-*': 'kiss.png', 
    ':*': 'kiss.png', 
    ':[email protected]': 'angry.png', 
    ':@': 'angry.png', 
    ':$': 'con2.png', 
    ':-$': 'con1.png', 
    'O.o': 'con2.png', 
    'o.O': 'con2.png', 
    ':/': 'weird.png', 
    ':x': 'x.png', 
    ':X': 'x.png', 
    ':!': 's.png', 
    '(:I': 'egg.png', 
    '^.^': 'kit.png', 
    '^_^': 'kit.png', 
    ';)': 'wink.png', 
    ';-)': 'wink.png', 
    ":')": 'hc.png', 
    ":'(": 'cry.png', 
    "|-O": 'yawn.png', 
    "-_-": 'poke.png', 
    ":|": 'p1.png', 
    "$_$": 'he.png' 

    }, url = "images/emo/"; 
    // a simple regex to match the characters used in the emoticons 
    return text.replace(/[:\-)D]+/g, function (match) { 

    return typeof emoticons[match] != 'undefined' ? 
      '<img class="emo" src="'+url+emoticons[match]+'"/>' : 
      match; 
    }); 
} 


replaceEmoticons("Hi this is a test string :) with all :P emos working :D"); 
+1

選中此[http://stackoverflow.com/questions/28077049/regex-matching-emoticons](http ://stackoverflow.com/questions/28077049/regex-matching-)[http://stackoverflow.com/questions/7317299/regex-matching-list-of-emoticons-of-various-type](http: stackoverflow.com/questions/7317299/regex-matching-list-of-emoticons-of-various-type) –

回答

2

此正則表達式:

[:\-)D]+ 

不匹配許多清單中的表情符號。除:,\,-,)D以外的任何字符都將阻止識別它。

如果你有一個你想要匹配的字符串列表,你可以輕鬆地構建一個正則表達式來匹配它們中的任何一個(並且沒有其他),通過轉義每個字符串並將它們與|連接在一起。事情是這樣的:

// given a string, return the source for a regular expression that will 
// match only that exact string, by escaping any regex metacharacters 
// contained within. 
RegExp.escape = function(text) { 
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 
} 

// build a regex that will match all the emoticons. Written out, it looks 
// like this: /:\)|: \)|:D|:->|:d|:-\)|:p|:P|..../g 
var emoticonRegex = 
    new RegExp(Object.keys(emoticons).map(RegExp.escape).join('|'), 'g'); 

然後用到位的字面正則表達式:

return text.replace(emoticonRegex, function (match) { ... 
+0

但是,如何可以寫一個正則表達式? (我相信這是OP要求的問題)。 –

+0

我正在接觸@cale_b。 :) –

+0

嗯,我已經能夠寫在我的字符串中的emos的所有符號,這似乎工作。任何人都可以解釋我如何正則表達式的作品?它是否需要內部每個角色的組合?這對我工作我只是不明白這是如何工作text.replace(/ [:; \ - )DPp(oO |><*!'] +/g,功能(匹配) – Faizan