开发者

jQuery detect and validate an URL

开发者 https://www.devze.com 2023-04-12 07:30 出处:网络
Let\'s imagine I have this text: Hi, my name is Pablo and my home page is http://zad0xsis.n开发者_C百科et

Let's imagine I have this text:

Hi, my name is Pablo and my home page is http://zad0xsis.n开发者_C百科et

How can I detect and validate the URL so it automatically wraps it into <a href="the detected url">the detected url</a>? Thanks!


You could use a regex:

var s = 'Hi, my name is Pablo and my home page is http://zad0xsis.net';
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
s = s.replace(exp,"<a href=\"$1\">$1</a>"); 
alert(s);

Live demo.


Can also try the jquery linkify plugin @ http://code.google.com/p/jquery-linkify/

Easy to use -

$('.section').linkify();

Pretty much does the same as mentioned by Darin.

0

精彩评论

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

关注公众号