如何使用RegEx在文本中转换表情符号?

时间:2015-02-27 15:01:08

标签: javascript regex

除了一个案例之外,以下正则表达式都适用。

如果我用“:-)开始一个文本”,那么表情符号应该被转换,而不是。我需要添加什么才能实现这一目标?

    // :-O :O :-o :o

    _message = _message.replace(/\s:-?[Oo]\s/g, '<i class="icon-emoji-freaked-mini"></i>');

    // :-) :)

    _message = _message.replace(/\s:-?\)\s/g, '<i class="icon-emoji-smile-mini"></i>');

    // :-D :D

    _message = _message.replace(/\s:-?D\s/g, '<i class="icon-emoji-laugh-mini"></i>');

    // :-( :(

    _message = _message.replace(/\s:-?\(\s/g, '<i class="icon-emoji-sad-mini"></i>');

    // ;-) ;)

    _message = _message.replace(/\s;-?\)\s/g, '<i class="icon-emoji-wink-mini"></i>');

    // :-/ :/ :-| :|      excluded: :-// ://  (URLs)

    _message = _message.replace(/\s:-?[\/\|](?!\/)\s/g, '<i class="icon-emoji-well-mini"></i>');

1 个答案:

答案 0 :(得分:1)

您可以使用^锚定到字符串的开头(当它在方括号外时具有此含义)。所以我们说<start of string or following a whitespace character>

我们也可以与$类似,并锚定到字符串的末尾。

// :-O :O :-o :o

_message = _message.replace(/(^|\s):-?[Oo](\s|$)/g, '<i class="icon-emoji-freaked-mini"></i>');

// :-) :)

_message = _message.replace(/(^|\s):-?\)(\s|$)/g, '<i class="icon-emoji-smile-mini"></i>');

// :-D :D

_message = _message.replace(/(^|\s):-?D(\s|$)/g, '<i class="icon-emoji-laugh-mini"></i>');

// :-( :(

_message = _message.replace(/(^|\s):-?\((\s|$)/g, '<i class="icon-emoji-sad-mini"></i>');

// ;-) ;)

_message = _message.replace(/(^|\s);-?\)(\s|$)/g, '<i class="icon-emoji-wink-mini"></i>');

// :-/ :/ :-| :|      excluded: :-// ://  (URLs)

_message = _message.replace(/(^|\s):-?[\/\|](?!\/)(\s|$)/g, '<i class="icon-emoji-well-mini"></i>');

此外,正如卡西米尔所说,你可以做这样的事情,利用这个事实,只要它以字母,_或$开头,javascript变量几乎可以包含任何字符。

_message = "He Loves me :), he loves me not. :(";

var Smiles = {"e:-O": "freaked-mini","e:O": "freaked-mini","e:-)": "smile-mini","e:)": "smile-mini","e:-D": "laugh-mini","e:D": "laugh-mini","e:-(": "laugh-mini","e:(": "laugh-mini","e;-)": "wink-mini","e;)": "wink-mini","e:-\\": "well-mini","e:\\": "well-mini","e:-\|": "well-mini","e:\|": "well-mini"}

_message = _message.replace(/(?:^|\s)(:-?[Oo]|:-?\)|:-?\(|:-?D|s:-?|;-?\)|:-?[\/\|](?!\/))(?=\s|$)/g,function (match,p1) {
        return '<i class="icon-emoji-' + Smiles["e" + p1] + '></i>';
    });

console.log(_message);

我遇到的一个问题是,无论代码样式是什么,它都不会捕获表情符号,紧接着是一个标点符号that makes me sad :(.

虽然可以轻松解决,但我们会将(?=\s|$)更改为(?=\s|$|\.|,|\?|\!)And that makes me happy<i class="icon-emoji-smile-mini></i>.

_message = _message.replace(/(?:^|\s)(:-?[Oo]|:-?\)|:-?\(|:-?D|s:-?|;-?\)|:-?[\/\|](?!\/))(?=\s|$|\.|,|\?|\!)/g,function (match,p1) {
        return '<i class="icon-emoji-' + Smiles["e" + p1] + '></i>';
    });

console.log(_message);