Extracting for URL from string using regex

前端 未结 3 1130
南旧
南旧 2020-12-21 08:34

I want to extract the first valid URL in a string, which can be anywhere between characters and whitespace

I have tried with the following

...
urlReg         


        
相关标签:
3条回答
  • 2020-12-21 08:54

    Your regex is incorrect.

    Correct regex for extracting URl : /(https?:\/\/[^ ]*)/

    Check out this fiddle.

    Here is the snippet.

    var urlRegex = /(https?:\/\/[^ ]*)/;
    
    var input = "https://medium.com/aspen-ideas/there-s-no-blueprint-26f6a2fbb99c random stuff sd";
    var url = input.match(urlRegex)[1];
    alert(url);

    0 讨论(0)
  • 2020-12-21 08:58

    That's because the match result holds the whole string first that matches, then the groups. I guess you want the group, so you can do this:

    url[1]
    

    Here's a fiddle: http://jsfiddle.net/jgt8u6pc/1/

    0 讨论(0)
  • 2020-12-21 09:04
    • You haven't included digits in your regex as part of URL.
    • Assuming URL starts from the beginning of the string

    Live Demo with regex explanation on left side.

    Regex explanation

    var regex = /^(https?:\/\/[^/]+(\/[\w-]+)+)/;
    var str = 'https://medium.com/aspen-ideas/there-s-no-blueprint-26f6a2fbb99c random stuff sd';
    
    var url = str.match(regex)[0];
    document.write(url);

    0 讨论(0)
提交回复
热议问题