请写一个函数按需求将字符串中的某些字符替换。
需求1:将以http://开头或者rss://开头的直到结束的字符段替换为<a>链接。
需求2:开头必须有空格(nbsp;等同于空格)或者<br/>算一个字符段的开始,第一个字符段可以没有
空格或者<br/>,结尾有空格或者<br/>算一个字符段的结束,否则直到字符串结束才算结束。For Example:'http://y.com.cn test1<br/>test2 &nbsp; &nbsp;rss://a.comghhttp://<br/>http://b.net http://c.cc<br/>test3'Results:(为了方便阅读,特意换行了)
'<a href="http://y.com.cn">http://y.com.cn</a> test1<br/>test2 &nbsp; &nbsp;
<a href="rss://a.com ghhttp://">rss://a.comghhttp://</a><br/>
<a href="http://b.net">http://b.net</a> <a href="http://c.cc">http://c.cc</a><br/>test3'测试页面:<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
    <style>a{color:#f30;}</style>
</head>
<body>
<div>
    <textarea id="a" style="border:1px solid #ccc;width:300px;height:140px;"></textarea>
    <input type="button" id="b" value="转换" />
    <div id="c"></div>
</div>
<script src="http://code.jquery.com/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="http://files.cnblogs.com/shuicaituya/htmlEncode.js" type="text/javascript"></script>
<script>
$("#a").val('http://y.com.cn test1\rtest2   rss://a.comghhttp://\rhttp://b.net http://c.cc\rtest3');
$("#b").bind("click",function(){
var input = htmlEncode($.trim($("#a").val()));
var reg = /((?:(?:https?)|(?:rss)):\/\/[\w\.]+?)(?: |(?:<br\/>)|(?:&nbsp;))/g;
var output = input.replace(reg,"<a href=\"$1\">$1</a>");
$("#c").html(output);
})
</script>
</body>
</html>
调试结果:
求助:
正则没有符合要求,求更好的正则。