gpt4 book ai didi

javascript - 如何编写用于查找 :smile: in javascript? 的正则表达式

转载 作者:行者123 更新时间:2023-11-30 20:15:34 26 4
gpt4 key购买 nike

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

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

^:.*\:$

最佳答案

我的猜测是您不仅要查找字符串,还要替换它。为此,您应该考虑将正则表达式中的捕获与替换函数结合使用。

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”或“big-smile-”。为此,您需要将模式更改为:

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

该模式正在寻找任何单词,然后是零个或多个连字符后跟一个单词的实例。它将匹配以下任何一项:“微笑”、“灿烂的笑容”、“灿烂的笑容”。

关于javascript - 如何编写用于查找 :smile: in javascript? 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51953284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com