【问题标题】:Removing the links from reddit comments从 reddit 评论中删除链接
【发布时间】:2018-05-18 13:00:39
【问题描述】:

我正在阅读 reddit 帖子下的 cmets。

有些 cmets 有链接,我想去掉。

示例(输入):

This is a [pic](https://i.imgur.com/yKmUMJD.jpg), [this](http://www.google.com) is a link

我希望字符串的外观(输出):

这是图片,这是链接

我使用了this,下面这行就可以了:

item.data.body.replace(/ *\([^)]*\) */g, "").replace('[', '').replace(']', '');

我想知道如何将http 添加到正则表达式中,这样它也不会删除“正常”括号文本。

谢谢

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    我看到你之前发布了一个类似的问题。现在您还发布了您尝试过的内容...看起来您正在努力解决这个问题。

    我会这样做:

    const str = "This is a [pic](https://i.imgur.com/yKmUMJD.jpg), [this](http://www.google.com) is a link";
    
    const tags = str.match(/\[.*?(?=\]\((.*?)\))/g).map(x => x.substring(1));
    const newString = str.replace(/\[.*?\]\(.*?\)/g, () => {
      return tags.shift();
    });
    
    console.log(newString)

    第一步是找到所有标记的文本。换句话说,所有内容都包含在[] 中。在上面的示例中,这将产生数组 [pic, this]

    然后,我们需要用上面的每个匹配项替换整个 url bbcode(即[xxx](http://url))。我们将数组视为一个队列,并在使用后使用 shift() 从数组中删除每个结果。

    当然,这个解决方案并非万无一失。它不会处理任何字符 ()[] 是标记或 URL 本身的一部分的极端情况。

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 2016-02-20
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 2014-03-02
      • 1970-01-01
      • 2020-10-22
      相关资源
      最近更新 更多