24

how to detect and get url on string javascript?

example :

var string = "hei dude, check this link http:://google.com and http:://youtube.com"

how to get result like this from my string :

var result = ["http:://google.com", "http:://youtube.com"]

how do that?

monoy suronoy
  • 881
  • 5
  • 10
  • 19
  • For URLs in natural language texts, there are many exceptions to consider. Why not use a library like this? https://github.com/Andrew-Kang-G/url-knife – Kang Andrew Jul 17 '20 at 08:27
  • 1
    Dupe isn't correct because OP is trying to find matches that look like URLs here but not wellformed URL due to use of double `::` after `http`. – anubhava Jun 17 '21 at 05:58

2 Answers2

54

You input has double :: after http. Not sure if it intentional. If it is then use:

var matches = string.match(/\bhttps?::\/\/\S+/gi);

If only one : is needed then use:

var matches = string.match(/\bhttps?:\/\/\S+/gi);

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643
6

const string = "hei dude, check this link http:://google.com and http:://youtube.com"
const matches = string.match(/\bhttp?::\/\/\S+/gi);
console.log(matches);
double-beep
  • 5,031
  • 17
  • 33
  • 41
QasimRamzan
  • 397
  • 3
  • 16