正则表达式查找文本块(Javascript)中的URL [英] Regular Expression to find URLs in block of Text (Javascript)

查看:112
本文介绍了正则表达式查找文本块(Javascript)中的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个Javascript正则表达式,扫描一个纯文本块,并以URL为链接返回文本。



这是我所拥有的:

 
findLinks:function(s){
var hlink = / \s(ht | f)tp:\ / \ / ([^ \,\; \:\!\)\(\\\\\\\\\\\\v])+ / g;
return(s.replace(hlink,function($ 0,$ 1,$ 2){
s = $ 0.substring(1,$ 0.length);
while(s.length> 0 && s .charAt(s.length - 1)=='。')s = s.substring(0,s.length - 1);

return''+ s +'';
));
}

问题是它只会匹配 http://www.google.com
和NOT google.com/adsense



如何完成两项?

解决方案iv>

我用这个a作为参考,这个家伙有8个正则表达式你应该知道。



http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-应该知道/



这是他用来查找URL的

  / ^(HTTPS:\?/ \ /?)。([\da-z\ .-] +)\([。az\] {2,6-}) ([\ / \w \ .-] *)* \ /?$ / 

他也分解了每个部分的作用。非常有用的学习正则表达式,而不只是得到一个答案,因为你不明白的原因。


I need a Javascript regular expression that scans a block of plain text and returns the text with the URLs as links.

This is what i have:

findLinks: function(s) {
          var hlink = /\s(ht|f)tp:\/\/([^ \,\;\:\!\)\(\"\'\\f\n\r\t\v])+/g;
          return (s.replace(hlink, function($0, $1, $2) {
              s = $0.substring(1, $0.length);
              while (s.length > 0 && s.charAt(s.length - 1) == '.') s = s.substring(0, s.length - 1);

              return ' ' + s + '';
          }));
      }

the problem is that it will only match http://www.google.com and NOT google.com/adsense

How could I accomplish both?

解决方案

I use this a as reference all the time. This guy has 8 regex's you should know.

http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-should-know/

Here is what he uses to look for URL's

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

He also breaks down what each part does. Very useful for learning regex's and not just getting an answer that works for reasons you don't understand.

这篇关于正则表达式查找文本块(Javascript)中的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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