• 使用js的正则表达式匹配字符串里的url,并对url进行修改后替换原来的url


    如果要匹配URL并且对其进行一定的修改后替换原来的URL,你需要一个函数,这个函数可以匹配URL,然后对匹配到的URL进行所需要的修改。下面是一个例子,展示了如何实现这样的功能:

    function replaceAndModifyUrls(text, modifyFn) {
      // 正则表达式匹配大部分URL
      const urlRegex = /(\bhttps?:\/\/[^\s]+(\b|$))/gi;
    
      // 这个函数会被用来修改找到的URL
      function modifyMatchedUrl(match) {
        // 这里可以根据需要对URL进行任何处理
        // modifyFn 是一个函数,接受原始的URL作为参数并返回修改后的URL
        return modifyFn(match);
      }
    
      // 替换发现的所有URL为经过modifyFn处理后的URL
      return text.replace(urlRegex, modifyMatchedUrl);
    }
    
    // 示例修改函数
    function addTrackingParam(url) {
      // 向URL添加一个假设的追踪参数
      const trackingParam = "utm_source=replaced";
      return url.includes('?') ? `${url}&${trackingParam}` : `${url}?${trackingParam}`;
    }
    
    const originalText = "Check out this website: https://example.com, or this link: http://example.net";
    // 使用 addTrackingParam 函数修改文本中匹配到的每个URL
    const newText = replaceAndModifyUrls(originalText, addTrackingParam);
    
    console.log(newText);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    在上面的代码中,我们定义了一个函数 replaceAndModifyUrls,它接收两个参数:

    1. text:要处理的文本字符串。
    2. modifyFn:一个用于修改匹配到的URL的函数。

    replaceAndModifyUrls 函数内部,使用 String.prototype.replace() 方法和正则表达式来找到所有的URL。replace() 的第二个参数是一个回调函数 modifyMatchedUrl,该函数将匹配到的URL传递给 modifyFn 函数,后者进行具体修改,并返回新的URL字符串。

    在此示例中,addTrackingParammodifyFn 的一个实现,它为每个URL添加了一个查询参数。当原始URL中已经包含其他查询参数,我们添加一个&,否则我们以?开头添加。

    运行上述代码时,console.log(newText) 的输出将是:

    Check out this website: https://example.com?utm_source=replaced, or this link: http://example.net?utm_source=replaced
    
    • 1

    请注意,正则表达式和修改函数需要根据你具体的需要进行调整,以处理各种可能出现的URL情况,如包含特殊字符、端口号、锚点等。

    人工智能学习网站

    https://chat.xutongbao.top/

  • 相关阅读:
    k8s上对Pod的管理部分详解
    八大排序(尚未完善)
    Matlab代码格式一键美化神器
    Objective-C网络数据捕获:使用MWFeedParser库下载Stack Overflow示例
    正确安装gdal库:ModuleNotFoundError: No module named ‘osgeo‘
    Python+Appium+Pytest+Allure实战APP自动化测试!
    模型评估与选择
    我的创作纪念日
    实现一个简单的哈希映射功能
    JAVA深化篇_36—— Java网络编程中的常用类
  • 原文地址:https://blog.csdn.net/xutongbao/article/details/137379685