Extract URLs from paragraph or block of text using a regular expression

I have a text and a script

var x = "This is an example url http://www.longurl.com/?a=example@gmail.com&x=y1 and this must me a example url";

function getMatch(str) {
  var urlRegex = '(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?';
  var reg = new RegExp(urlRegex, 'ig');
  return str.match(reg);
}

console.log(getMatch(x));

The expected outcome must be

[ http://www.longurl.com/?a=example@gmail.com&x=y1 ] 

but the below getMatch is giving me incorrectly (skipping &x=y1)

http://www.longurl.com/?a=example@gmail.com

How do I modify the function to return a complete URL

NOTE: This happens only when the email arguments are passed after it
finds @ character, the function behaves weird.

98 thoughts on “Extract URLs from paragraph or block of text using a regular expression”

  1. i need a direct payday loan lender, i need consolidation loan. i need car loan for bad credit need loan i need a loan today i need a loan desperately, cash advance loans direct lender, cash advances, cash advances, money 3 payday loans. Commerce study of those money management, financial institution .

    Reply

Leave a Comment