开发者

Call a function if a valid URL is found in a textarea

开发者 https://www.devze.com 2023-02-09 13:03 出处:网络
开发者_JAVA百科What would be the best way to immediately call a function (myFunction()) as soon as a valid URL has been typed into a textfield? I\'ve googled around but I haven\'t found anything that
开发者_JAVA百科

What would be the best way to immediately call a function (myFunction()) as soon as a valid URL has been typed into a textfield? I've googled around but I haven't found anything that helps. Using a regular expression would probably be best but I need one that recognizes all sorts of URLs:

http://google.tld, www.google.tld, http://www.google.tld But still doesn't consider things like "index.php" to be a URL. Does anyone know about such an expression?


^((?:https?|ftp):\/\/)?([\w\.]+.)([a-z]{2,4})$

Supports ftp as well ;)


You might struggle a bit as there would be so many different possibilities. This one will match any url that is technically a valid http or https path (which includes any character in the path after the domain name, any number of subdomains, etc)

((http)s?(://))?[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*(/(.*))?

Of if you'd like to exclude intranets, you can force a tld using the following:

((http)s?(://))?[a-zA-Z0-9\-]+(\.[a-zA-Z0-9]+)*(\.[a-zA-Z0-9]{2,4})+(/(.*))?


this will match any URL that ends with something like '.com' or '.ch' (you have to maintain the list of valid TLDs)

^(http:\/\/)?([\w\.]+\.)((com)|(ch))$

with javascript the forwardslash doesn't need escaping and TLDs could be less strict e.g. just something with 2-4 characters.

^(https?://)?([\w\.]+\.)([a-z]{2,4})$

Considering a comment to this question by CanSpice the idea of allowing TLDs with different length is difficult to cover as the event trigger may fire too early. A time delay upon the onchange trigger may solve this kind of issues. Precise requirements and pros/cons of each solution should be weighted.

example at rubular

0

精彩评论

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

关注公众号