26

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?

2
  • For URLs in natural language texts, there are many exceptions to consider. Why not use a library like this? github.com/Andrew-Kang-G/url-knife Commented Jul 17, 2020 at 8: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. Commented Jun 17, 2021 at 5:58

2 Answers 2

58

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

Sign up to request clarification or add additional context in comments.

5 Comments

100% right.. i am also do this..
var matches = string.match(/\bhttp?::\/\/\S+/gi); console.log(matches)
great @anubhava thank you
It seems that it doesn't detect: "youtube.com/watch?v=eogv_ItM9s8"
That is not that simple. You have to consider many exceptional cases.
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.