Regex match string before space 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 above examples and up to the next space, thus the entire url.

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

      

Suppose I have a line that looks like this:

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

I want to run a match on this line and get

www.stackoverflow.com

Thank!

+3


source to share


3 answers


You may try

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

      

Here is an online demo

example 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);

      

Explanation of the pattern:

  (?:                      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)

      

+4


source


You have an error in your regex.

Use this:

((\s))(http?:\/\/)|(https?:\/\/)|(www\.)(?!\s{1})
                                          ^--- Change to negative lookaround

      



By the way, I think you can use:

(?:(http?:\/\/)|(https?:\/\/)|(www\.))(?!\s{1})

MATCH 1
3.  [0-4]   `www.`
MATCH 2
1.  [16-23] `http://`
MATCH 3
2.  [35-43] `https://`

      

0


source


Not really sure what you are trying to do, but it should match any group of nonspatial characters not immediately preceded by "www". case insensitive.

/(https?:\/\/)?(?<!(www\.))[^\s]*/i

      

... [edit] but you would like to match www.

/(https?:\/\/)?([^\s\.]{2,}\.?)+/i

      

0


source







All Articles