gpt4 book ai didi

Javascript 正则表达式解析表情符号并忽略 url

转载 作者:行者123 更新时间:2023-11-30 16:32:23 24 4
gpt4 key购买 nike

我想解析来自用户的输入并用笑脸图像替换所有笑脸“代码”。当用户编写 url 然后 http://和 https://的 :/被替换时,我遇到了一个问题。我用于 :/替换的当前正则表达式是“/://g”,我需要帮助更改它,以便它不会替换 :/如果它位于 http://或 https://

输入示例

Please have a look at this link http://stackoverflow.com that could help you :). If it does not help :/ then please use https://www.google.com

应该解析输出

Please have a look at this link http://stackoverflow.com that could help you <img src="/smile.png"/>. If it does not help <img src="/sidesmile.png"/> then please use https://www.google.com

这是一个 regex101.com 示例:https://regex101.com/r/bB6vK2/1 (如您所见,http://和 https://也被选中并在此处替换)

最佳答案

您可以匹配并捕获要保留的:/,只匹配将被替换的:/

/((?:https?|ftps?):\/)|:\//ig

看,((?:https?|ftps?):\/)就是:/ 前面有http 或者ftp,它们可以在replace 中的匿名函数中恢复。

这是一个片段:

var str = 'Please have a look at this link http://stackoverflow.com that could help you :). If it does not help :/ then please use https://www.google.com. Now, a difficult one:/';
var result = str.replace(/((?:https?|ftps?):\/)|:\//ig, function (m, grp1) {
return grp1 ? grp1 : '<img src="/sidesmile.png"/>';
});
alert(result);

关于Javascript 正则表达式解析表情符号并忽略 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33147431/

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