首页 > Web开发 > 详细

正则表达式识别字符串中的URL

时间:2016-11-05 23:26:08      阅读:311      评论:0      收藏:0      [点我收藏+]

一般我们经常看到一些在帖子或者别人的文章里,文字中间还会夹带着很多的网址还有URL而且URL还是可以点击进去的;还有另外一个较常用到的地方就是聊天系统中识别对话的URL,废话不多说,入正题请看下面的代码!

// 从字符串中提取url  
    function matchUrl(str){  
        res = str.replace(/((?:http:\/\/)(?:.[\w]+)+)/g,function(){  
            if (/^http/.test(arguments[1]))  
            {  
                return "<a class=‘urlTag‘" + " onclick=webPage(‘"+arguments[1]+"‘) "  +"href=‘javascript:void(0)‘>"+arguments[1]+"</a>";  
            } else {  
                return "<a class=‘urlTag‘" + " onclick=webPage(‘http://"+arguments[1]+"‘) " +"href=‘javascript:void(0)‘>"+arguments[1]+"</a>";  
            }  
        });  
        return res;  
    }  
result = matchUrl(‘http://blog.csdn.net/jacko_chan这是我的博客网站‘);  

alert(result);

(上面的正则是匹配URL没有www开头,如果有需要可以加个判断)

<script type="text/javascript">  
    str = ‘http://www.baidu.com‘;  
    result = str.match(/((?:http:\/\/)?w{3}(?:.[\w]+)+)/g);  
    if (result == null) {  
        result = str.match(/((?:http:\/\/)?(?:.[\w]+)+)/g);  
    };  
    document.write(result);  
</script> 

正则表达式识别字符串中的URL

原文:http://www.cnblogs.com/jacko/p/6034134.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!