题目描述:
给段文本,里面会有包含https,http,www.开头的,将这些转化为一个链接,可以打开一个新窗口,www的默认以http开头
麻烦之处:
www的被包含到了https或http中,不能重复识别,因此这里构建一个数据结构,先将每个识别到的保存到一个字典中(对象),然后先将这里替换为一个具有标记的特殊字符(这里就是’cuihu[数字]cuihu’),然后根据数字再将先前保存的读出相应的(这里已经转化为a标签的相关代码),
注意一点,识别非的时候会识别前面多以为,比如www不能匹配http:\,然后这样a.match(/[^http:\\]www)时,会识别满足条件但w前一位会识别,下面代码(第一次做,无法完美解决验证,只有60%通过)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
a {
color: #00bc9b;
}
</style>
<body>
<div id="t1">
<div id="jsContainer">
这里会给出一段随机文本,可能包含一些链接,比如https://www.baidu1.com,或者 www.baidu2.com?from=onlineExam,如果出现链接文本,http://www.baidu3.com请给该链https://www.baidu4.com接文本加上链接www.baidu5.com标签,用户点击后能www.baidu6.com直接在https://www.badu7.com新窗口中https://www.baid8.com打开该链接。
</div>
</body>
<script>
window.onload = function(){
function link() {
var doc = window.document ;
var text = doc.getElementById('jsContainer');
var tx = text.innerHTML ;
var newst = '';
var k ='';
var all = {};
var num = 0 ;
var num2 = 0;
tx=tx.replace(/https\:\/\/[\w|\?|\.|\=]+/g,function(word){
k=word.slice(1,word.length);
newst ='<a target="_blank" href=\"'+word+'">'+word+'</a>';
all['cuihu'+num]=newst ;
num2= num ;
num++;
return 'cuihu'+num2+'cuihu' ;
});
tx=tx.replace(/http\:\/\/[\w|\?|\.|\=]+/g,function(word){
newst = '<a target="_blank" href=\"'+word+'">'+word+'</a>';
all['cuihu'+num] =newst;
num2=num ;
num++;
return 'cuihu'+num2+'cuihu' ;
});
tx=tx.replace(/[^http\:\\\\|https\:\\\\]www\.[\w|\?|\.|\=]+/g,function(word){
console.log(word[0]);
console.log(word);
k=word.slice(1,word.length);
//console.log(word);
newst = word[0]+'<a target="_blank" href="http:\\\\'+k+'">'+k+'</a>';
all['cuihu'+num]=newst ;
console.log(newst);
num2=num ;
num++;
return 'cuihu'+num2+'cuihu' ;
});
console.log(all);
tx=tx.replace(/cuihu\d+cuihu/g,function(word){
//console.log(word);
var newnu = word.match(/\d+/);
//console.log(newnu);
return all['cuihu'+newnu];
});
text.innerHTML= tx ;
}
link();
}
</script>
</html>