0

I want to match the First url followed by a space using regex expression while typing in the input box. For example : if I type www.google.com it should be matched only after a space followed by the url ie www.google.com<SPACE>

Code

$(".site").keyup(function()
{
   var site=$(this).val();
   var exp = /^http(s?):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
   var find = site.match(exp);

   var url = find? find[0] : null;

        if (url === null){
        var exp = /[-\w]+(\.[a-z]{2,})+(\S+)?(\/|\/[\w#!:.?+=&%@!\-\/])?/g;
        var find = site.match(exp);
        url = find? 'http://'+find[0] : null;
      }
});

Fiddle

Please help, Thanks in advance

user3357227
  • 119
  • 1
  • 2
  • 10

2 Answers2

1

you should be using a better regex to correctly match the query & fragment parts of your url. Have a look here (What is the best regular expression to check if a string is a valid URL?) for a correct IRI/URI structured Regex test.

But here's a rudimentary version:

var regex = /[-\w]+(\.[a-z]{2,})+(\/?)([^\s]+)/g;
var text = 'test google.com/?q=foo basdasd www.url.com/test?q=asdasd#cheese something else';
console.log(text.match(regex));

Expected Result:

["google.com/?q=foo", "www.url.com/test?q=asdasd#cheese"]

If you really want to check for URLs, make sure you include scheme, port, username & password checks just to be safe.

In the context of what you're trying to achieve, you should really put in some delay so that you don't impact browser performance. Regex tests can be expensive when you use complex rules especially so when running the same rule every time a new character is entered. Just think about what you're trying to achieve and whether or not there's a better solution to get there.

Community
  • 1
  • 1
Justin Mitchell
  • 319
  • 1
  • 5
0

With a lookahead:

var exp = /[-\w]+(\.[a-z]{2,})+(\S+)?(\/|\/[\w#!:.?+=&%@!\-\/])?(?= )/g;

I only added this "(?= )" to your regex.

Fiddle

Raul Guiu
  • 2,285
  • 20
  • 34