JS中关于正则的巧妙操作

var msg="dsada[emoji:37]dsadas[emoji:3900]法拉綏芬河";
function fetch(msg) {
    var match, result = msg,
        reg = /\[emoji:\d+\]/g,
        emojiIndex,
        totalEmojiNum = 45;
    while (match = reg.exec(msg)) {
        console.log(match[0]);//[emoji:37],[emoji:3900]
        emojiIndex = match[0].slice(7, -1);
        console.log(emojiIndex);//37,3900
        if (emojiIndex > totalEmojiNum) {
            result = result.replace(match[0], '[X]');
        } else {
            result = result.replace(match[0], '<img src="images/eomji_' + emojiIndex + '.gif" />');
        };
    };
    return result;//"dsada<img src="images/eomji_37.gif" />dsadas[X]法拉綏芬河"
}
fetch(msg);

 

posted @ 2017-08-31 16:21  逗伴不是瓣  阅读(501)  评论(0编辑  收藏  举报