Search code examples
javascriptregexstringwhitespace

Regex match string until whitespace Javascript


I want to be able to match the following examples:

www.example.com
http://example.com
https://example.com

I have the following regex which does NOT match www. but will match http:// https://. I need to match any prefix in the examples above and up until the next white space thus the entire URL.

var regx = ((\s))(http?:\/\/)|(https?:\/\/)|(www\.)(?=\s{1});

Lets say I have a string that looks like the following:

I have found a lot of help off www.stackoverflow.com and the people on there!

I want to run the matching on that string and get

www.stackoverflow.com

Thanks!


Solution

  • You can try

    (?:www|https?)[^\s]+
    

    Here is online demo

    sample code:

    var str="I have found a lot of help off www.stackoverflow.com and the people on there!";
    var found=str.match(/(?:www|https?)[^\s]+/gi);
    alert(found);
    

    Pattern explanation:

      (?:                      group, but do not capture:
        www                      'www'
       |                        OR
        http                     'http'
        s?                       's' (optional)
      )                        end of grouping
      [^\s]+                   any character except: whitespace 
                                (\n, \r, \t, \f, and " ") (1 or more times)