18

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
  • 781
  • 4
  • 8
  • 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

48

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
  • 713,503
  • 59
  • 514
  • 593
5

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
  • 4,567
  • 13
  • 30
  • 40
QasimRamzan
  • 387
  • 3
  • 16