Parsing text with multiple links using regex in javascript

Hi im has text containing some links wrapped inside text ...

I want a regular expression (I use javascript) that can parse text and return an array of links ...

for example, for text ...

http://www.youtube.com/watch?v=-LiPMxFBLZY
testing
http://www.youtube.com/watch?v=Q3-l22b_Qg8&feature=related

regex will parse the text and return an array of links

arr[0] = "http://www.youtube.com/watch?v=-LiPMxFBLZY"
arr[1] = "http://www.youtube.com/watch?v=Q3-l22b_Qg8&feature=related"

I am trying to do this with code ...

var ytre =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig ;
var matches = new Array();

                    matches = ytre.exec(text);
                    var jm;
                    if (matches !=null )
                    {
                        for (jm=0; jm<matches.length; jm++)
                        {
                            console.log(matches[jm]);
                        }
                    }

but does not return the corresponding results ...

please, help

thank

+3
source share
2 answers

What about:

var text = 'http://www.youtube.com/watch?v=-LiPMxFBLZY testing http://www.youtube.com/watch?v=Q3-l22b_Qg8&feature=related http://yahoo.com';

var ytre = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z0-9+&@#\/%=~_|])/ig;

var resultArray = text.match(ytre);

Take a look

+8
source

To parse URLs using regular expressions, see the RFC, which defines URLs.

, , , , /\b(([^:\/?#]+):)(\/\/([^\/?#]*))([^?#]*)(\?([^#]*))?(#(.*))?/gi.

http://www.ietf.org/rfc/rfc3986.txt

B. URI

"first-match-wins" ""
, POSIX , URI .

-

URI .

  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
   12            3  4          5       6  7        8 9

, ; (.. ). , $. ,

  http://www.ics.uci.edu/pub/ietf/uri/#Related

:

  $1 = http:
  $2 = http
  $3 = //www.ics.uci.edu
  $4 = www.ics.uci.edu
  $5 = /pub/ietf/uri/
  $6 = <undefined>
  $7 = <undefined>
  $8 = #Related
  $9 = Related

, , .

  scheme    = $2
  authority = $4
  path      = $5
  query     = $7
  fragment  = $9
+6

Source: https://habr.com/ru/post/1782677/


All Articles