0

I want to get a url from a string but I am unfamiliar with the use of regex or any such methods.

For example i have 3 strings,

  1. "I've navigated to www.facebook.com";
  2. "I've navigated to www.facebook.com and to www.google.com";
  3. "I've navigated to https://www.facebook.com ;

In my case : I should get "www.facebook.com" as the url that is extracted from the first string.

All I want is to get the first url inside the string so i can make a link preview using an API I found. But I am struggling to get the url using Javascript or Jquery. The string will be gotten from a textbox and I want to get the url on keyup.

stark
  • 2,246
  • 2
  • 23
  • 35
Romnick Susa
  • 1,279
  • 13
  • 31
  • Okay wait, I'll post it. – Romnick Susa Jan 28 '16 at 02:03
  • 1
    Tons of examples out there on the InterWebs, including lots here at StackOverflow. Please research before posting here unless you can state a special case where the other examples don't fit. https://www.google.com/search?q=javascript+regex+to+detect+url&oq=javascript+regex+to+detect+url – Tony Hinkle Jan 28 '16 at 02:20
  • Well already tried to google it. But examples are not fitting on my case. I need to check entire string IF theres is a url inside the string but examples given were just checking if string is a url. Just like what i've said, i dont know much in regex. – Romnick Susa Jan 28 '16 at 02:26
  • Answers, however simple, will make much more sense to you when you've at least attempted to do it and have something to show, however small! – PeterKA Jan 28 '16 at 02:28
  • Possible duplicate of [What is a good regular expression to match a URL?](http://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url) – Tushar Jan 28 '16 at 03:08

1 Answers1

2

You can use this function to extract the first URL found in the given string:

function getFirstUrl(string) {
    var pattern = /(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/;
    var match = string.match(pattern);
    return match[0];
}

var string = "I've nagivated to www.facebook.com and to www.google.com";
var url = getFirstUrl(string);
// url === 'www.facebook.com'

I got the regex pattern from this answer and modified it to make the https:// part optional.

Community
  • 1
  • 1
Arnelle Balane
  • 5,437
  • 1
  • 26
  • 32