JavaScript Regex to match a URL in a field of text

前端 未结 8 1275
一向
一向 2020-12-01 02:01

How can I setup my regex to test to see if a URL is contained in a block of text in javascript. I cant quite figure out the pattern to use to accomplish this



        
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 02:43

    Here's the most complete single URL parsing pattern.

    It works with ANY URI/URL in ANY substring!

    https://regex101.com/r/jO8bC4/5

    Example JS code with output - every URL is turned into a 5-part array of its 'parts':

    var re = /([a-z]+\:\/+)([^\/\s]*)([a-z0-9\-@\^=%&;\/~\+]*)[\?]?([^ \#]*)#?([^ \#]*)/ig; 
    var str = 'Bob: Hey there, have you checked https://www.facebook.com ?\n(ignore) https://github.com/justsml?tab=activity#top (ignore this too)';
    var m;
    
    while ((m = re.exec(str)) !== null) {
        if (m.index === re.lastIndex) {
            re.lastIndex++;
        }
        console.log(m);
    }
    

    Will give you the following:

    ["https://www.facebook.com",
      "https://",
      "www.facebook.com",
      "",
      "",
      ""
    ]
    
    ["https://github.com/justsml?tab=activity#top",
      "https://",
      "github.com",
      "/justsml",
      "tab=activity",
      "top"
    ]
    

    BAM! RegEx FTW!

提交回复
热议问题