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


一般我们经常看到一些在帖子或者别人的文章里,文字中间还会夹带着很多的网址还有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://www.cnblogs.com/jacko这是我的博客网站');  

alert(result);

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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM