Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 851
user1876246 Avatar asked Aug 11 '14 17:08

user1876246


People also ask

How to match whitespace in regex?

\s\d matches a whitespace character followed by a digit. [\s\d] matches a single character that is either whitespace or a digit. When applied to 1 + 2 = 3, the former regex matches 2 (space two), while the latter matches 1 (one).

How do I match a character except space in regex?

[^ ] matches anything but a space character.

What is\\ in regex?

To match a literal space, you'll need to escape it: "\\ " . This is a useful way of describing complex regular expressions: phone <- regex(" \\(? #

How to use end of string regex?

The correct regex to use is ^\d+$. Because “start of string” must be matched before the match of \d+, and “end of string” must be matched right after it, the entire string must consist of digits for ^\d+$ to be able to match.

How do you match something before a word in regex?

Take this regular expression: /^[^abc]/ . This will match any single character at the beginning of a string, except a, b, or *c. If you add a * after it – /^[^abc]*/ – the regular expression will continue to add each subsequent character to the result, until it meets either an a , or b , or c .


1 Answers

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)
like image 138
Braj Avatar answered Oct 09 '22 17:10

Braj