我想用JavaScript编写一个正则表达式,以查找以:开头和结尾的字符串。

例如,从该字符串中找到"hello :smile: :sleeping:",我需要找到以:字符开头和结尾的字符串。我尝试了下面的表达式,但是没有用:

^:.*\:$

最佳答案

我的猜测是,您不仅要查找字符串,而且还要替换它。为此,您应该查看将regexp中的捕获与替换功能结合使用。

const emojiPattern = /:(\w+):/g

function replaceEmojiTags(text) {
    return text.replace(emojiPattern, function (tag, emotion) {
        // The emotion will be the captured word between your tags,
        // so either "sleep" or "sleeping" in your example
        //
        // In this function you would take that emotion and return
        // whatever you want based on the input parameter and the
        // whole tag would be replaced
        //
        // As an example, let's say you had a bunch of GIF images
        // for the different emotions:
        return '<img src="/img/emoji/' + emotion + '.gif" />';
    });
}


使用该代码,您可以在任何输入字符串上运行函数,并替换标签以获取其中的实际图像的HTML。如您的示例:

replaceEmojiTags('hello :smile: :sleeping:')
// 'hello <img src="/img/emoji/smile.gif" /> <img src="/img/emoji/sleeping.gif" />'


编辑:为了在情感中支持连字符,就像在“大微笑”中一样,该模式需要更改,因为它只是在寻找单词字符。为此,可能还存在一个限制,即连字符必须连接两个单词,以使其不应接受“ -big-smile”或“ big-smile-”。为此,您需要将模式更改为:

const emojiPattern = /:(\w+(-\w+)*):/g


该模式正在寻找任何单词,然后跟随零个或多个连字符实例,再跟一个单词。它将与以下任何一个匹配:“微笑”,“大微笑”,“大微笑-更大”。

10-06 07:44