JavaScript Regexp在锚点中包装URL和电子邮件 [英] JavaScript Regexp to Wrap URLs and Emails in anchors

查看:110
本文介绍了JavaScript Regexp在锚点中包装URL和电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了高低,但无法找到确定的答案。正如regexp的情况一样。所以我想我会在这里问。

I searched high and low but cannot aeem to find a definitve answer to this. As is often the case with regexps. So I thought I'd ask here.

我正在尝试整理一个正则表达式,我可以在JavaScript中使用它来替换所有URL和电子邮件地址的实例( 需要非常严格,锚标签指向它们。

I'm trying to put together a regular expression i can use in JavaScript to replace all instances of URLs and email addresses (does'nt need to be ever so strict) with anchor tags pointing to them.

显然这通常是在服务器端非常简单地完成的,但在这种情况下它有必要使用纯文本,所以优雅的JavaScript解决方案在运行时进行替换将是完美的。

Obviously this is something usually done very simply on the server-side, but in this case it is necessary to work with plain text so an elegant JavaScript solution to perfom the replaces at runtime would be perfect.

Onl问题是,正如我之前所说,我有在我的技能组合中形成一个巨大的正则表达形状的大洞:(

Onl problem is, as I've stated before, I have a huge regular expression shaped gaping hole in my skill set :(

我知道你们中的一个人在你的指尖有了答案:)

I know that one of you has the answer at the tip of your fingers though :)

推荐答案

好吧,盲目地使用来自 http://www.osix.net/modules/article/?id=586

Well, blindly using regexps from http://www.osix.net/modules/article/?id=586

var emailRegex = 
   new RegExp(
   '([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}' + 
   '\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.' + 
   ')+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)',
   "gi");

var urlRegex = 
   new RegExp(
   '((https?://)' + 
   '?(([0-9a-z_!~*\'().&=+$%-]+: )?[0-9a-z_!~*\'().&=+$%-]+@)?' + //user@ 
   '(([0-9]{1,3}\.){3}[0-9]{1,3}' + // IP- 199.194.52.184 
   '|' + // allows either IP or domain 
   '([0-9a-z_!~*\'()-]+\.)*' + // tertiary domain(s)- www. 
   '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.' + // second level domain 
   '[a-z]{2,6})' + // first level domain- .com or .museum 
   '(:[0-9]{1,4})?' + // port number- :80 
   '((/?)|' + // a slash isn't required if there is no file name 
   '(/[0-9a-z_!~*\'().;?:@&=+$,%#-]+)+/?))',
   "gi");

然后

text.replace(emailRegex, "<a href='mailto::$1'>$1</a>");

text.replace(urlRegex, "<a href='$1'>$1</a>");

可能有效

这篇关于JavaScript Regexp在锚点中包装URL和电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆