开发者

Javascript regex only matching entire url as typing

I'm trying to use javascript to find all URLs in a textarea as the person is typing (onkeyup). The problem that I'm having is in finding a regex to match the entire URL, I need it only to match all the URL's in the text area that are complete URLs.

All of the existing regex expressions that I find through Google and through my own experiementing seem to match as soon as the user has typed the first part of the pattern. So, for example, if I'm typing and then start to type http://w, all of a sudden, it will match.

I need to find a regex that will match and return an array of all the urls that are in the textarea, while also not matching unless the person has completed typing the full URL. Hop开发者_StackOverflowefully that makes sense!

Thank you!


David's comment is right.

How could you ever determine that http://www.domain.com/whatever was a complete URL but http://www.domain.com/what wasn't? Or http://www.domain.com is complete but http://www.domain.co isn't? (It is, there's a real site there).

You might disallow hostnames without a . in, but then why shouldn't http://to be valid? (It is, there's a real site there.) Not to mention http://テスト.

There is no possible consistent answer to the question “what is the regex to match things that look like URLs to me”.


I ended up using this pattern:

   var pattern = /((https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])(\s|\.\s|\,\s|\n|\r|\n\r)/ig;

That checks for the existence of either a space or a carriage return (in conjunction with a comma or a period, I'll probably have to add some other cases), and then I remove the period or comma after.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜