1

I am trying to find URL form a sting. I want to check if string contain any URL.

For that sake i wrote code :

function get_url_from_string(str) {
        var searchText = str,
          urls = searchText.match(/\b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})\b/ig);
         for (var i = 0, il = urls.length; i < il; i++) {
            var ur=urls[i];
        }
        return ur;

    }

But it returning only URL with out any parameter. For Example if i pass:

Hi Check This https://www.youtube.com/watch?v=eHOc-4D7MjY

It gives me https://www.youtube.com Only

I want to get full url. I have no idea of regular expression. Please help. Thanks

5
  • Try \b(?:https?)?(:\/\/)?\S*\.\w{2,4}[^\s]+ Commented Dec 10, 2015 at 5:42
  • It is showing error. Commented Dec 10, 2015 at 5:44
  • This \.(\w{2,4} says match a . then 2-4 characters of [a-zA-Z0-9_]. So your expression ends at the .com. Adding \S* after the \w{2,4} would allow it to continue until it hit a whitespace. regex101.com/r/rI1nN4/1 Commented Dec 10, 2015 at 5:49
  • I have done it my self \b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})\b.(\S*) :) Thanks For your help. Commented Dec 10, 2015 at 5:49
  • You also can simplify the (http|https)? into `(https?)? Commented Dec 10, 2015 at 5:51

3 Answers 3

2

try this -

/\b(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?\s/
Sign up to request clarification or add additional context in comments.

Comments

2

Try This it works well for me.

      var url_regex = /(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?/gi;
      var text = "some text string here!!";
      var urls_array = [];
      while ((urls = url_regex.exec(text)) !== null) {
                            urls_array.push(urls[0]);
                    }

This code is used in my project

Comments

2

function get_url_from_string(str) {
 
        var searchText = str,
          urls = searchText.match(/\b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})?(.*)\b/ig);
         for (var i = 0, il = urls.length; i < il; i++) {
            var ur=urls[i];
        }
  alert(ur);
  
        return ur;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="x" onclick="get_url_from_string('https://www.youtube.com/watch?v=eHOc-4D7MjY')">click here
</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.