0

I am trying to pull out all the URLs from a text entered by the user by doing the following but am not able to get the desired result.

let regexp = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/igm;
let str = "https://mysleepyhead.com http://skreem.io";

let array = [...str.matchAll(regexp)];

console.log(array);

Desired output would be

Array ['https://mysleepyhead.com', 'http://skreem.io']
Harsha M V
  • 50,335
  • 109
  • 326
  • 496
  • `^` and `$` anchor to the beginning and end of the line. If the string you're dealing with is composed of multiple possible matches in a single line, don't use those anchors. https://regex101.com/r/q89Ipv/1 (you also probably want `.match`, not `.matchAll`) – CertainPerformance Feb 20 '20 at 06:12
  • @CertainPerformance i tried that. but when i do a match i am getting back null. would you be able to share a jsfidle or something. – Harsha M V Feb 20 '20 at 06:43
  • `"https://mysleepyhead.com http://skreem.io".match(/(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+/igm)` – CertainPerformance Feb 20 '20 at 06:44
  • @CertainPerformance some reason its matching other data as well. https://jsfiddle.net/4ubpL9we/ – Harsha M V Feb 20 '20 at 06:59
  • You made the leading `http` optional. Maybe you want to make sure the match contains at least one `.` in it? `(?:http(s)?:\/\/)?(?=[a-z])[\w-]+(?:\.[\w-]+)+(?:\/\S*)?` or something of the sort – CertainPerformance Feb 20 '20 at 07:11

0 Answers0