使用正则表达式和JavaScript来使链接可以点击但不会覆盖预先存在的链接? [英] Using regex and javascript to make links clickable but not overwrite pre-existing links?

查看:139
本文介绍了使用正则表达式和JavaScript来使链接可以点击但不会覆盖预先存在的链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用javascript制作可点击的链接,我认为正则表达式是最简单的,没有提及最快的方式。我希望所有链接都是可点击的,并且不会重写现有的已经可点击的链接。

I need to make links clickable using javascript and I thought regex would be the easiest not to mention fastest way. I want all links to be clickable, and to not rewrite the already clickable links that exist.

Example: 
Here is a link to visit http://www.example.com/page Please take a look <a href="http://www.example.com/page">here</a>.

Becomes: Here is a link to visit <a href="http://www.example.com/page">http://www.example.com/page</a> Please take a look <a href="http://www.example.com/page">here</a>.

Another example: Here is a link to visit http://www.example.com/page Please take a look here: <a href="http://www.example.com/page">http://www.example.com/page</a>

Becomes: Here is a link to visit <a href="http://www.example.com/page">http://www.example.com/page</a> Please take a look here: <a href="http://www.example.com/page">http://www.example.com/page</a>

And finally: <p id="demo">http://example.com/
<br><a href="http://example.com/123">http://example.com/123</a>
<br><a href="http://Google.ca/">http://Google.ca/</a></p>


推荐答案

这应该可以解决问题:

var pattern = new RegExp("[^\"'](http://[^ ]*)","g");
var newContent = yourString.replace(pattern," <a href=\"$1\">$1</a>");

要注意评论:

var pattern = new RegExp("([^\"'])(http://[^ ]*)","g");
var newContent = yourString.replace(pattern,"$1<a href=\"$2\">$2</a>");

评论后再进行一次编辑,前一个编辑认为链接不在开头:

One more edit after comment, the previous one asumed the link was not at the beginning:

var pattern = new RegExp("([^\"']||^)(http://[^ ]*)","g");
var newContent = yourString.replace(pattern,"$1<a href=\"$2\">$2</a>");

你可能已经看到了这个模式,在正则表达式中,inside()中的内容被赋予返回参数$ 1和$ 2 in在这种情况下,在替换语句中使用了witch来重建字符串。这里的模式必须进一步扩展,因为你遇到了其他没有被模式捕获的异常,例如把链接放在里面()就不会给出所需的结果。使用正则表达式的好网站是 regextester.com

You have probably seen the pattern already, in regular expressions what is inside () are asigned to a return parameter $1 and $2 in this case, witch is is used in the replace statement to rebuild the string.. The pattern here must probably be extended further as you come across other exceptions not catched by the pattern, for instance putting the link inside () would not give the desired result. A nice site to play with regular expressions is regextester.com

这篇关于使用正则表达式和JavaScript来使链接可以点击但不会覆盖预先存在的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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