// 题目描述
// 页面中存在id=jsContainer的DOM元素。
// 该DOM元素内会给出一段随机文本,可能包含一些链接,比如https://www.baidu.com,或者 www.baidu.com?from=onlineExam,如果出现链接文本,请给该链接文本加上链接标签,用户点击后能直接在新窗口中打开该链接。
// 请完成 link 函数,完成该功能
// 1、container只有纯文本内容,不包含其他dom元素
// 2、识别所有以http://、https://或者www.开始的链接
// 3、所有www.开头的链接,默认使用 http 协议
// 4、所有链接在新窗口打开
1. 自己的练习
<style>
a {
color: #00bc9b;
}
</style>
<div id="jsContainer">
这里会给出一段随机文本,可能包含一些链接,比如https://www.baidu.com,或者
www.baidu.com?from=onlineExam,如果出现链接文本,请给该链接文本加上链接标签,用户点击后能直接在新窗口中打开该链接。
</div>
function link() {
var str = document.querySelector('#jsContainer').innerText
alink = str.match(/(http(s)*:\/\/)?www\.(\w+\.)+\w+([?&#=\w]+)*/g)
if (alink) {
alink.forEach(item => {
model = item.startsWith('www.') ? 'http://' + item : item
str = str.replace(item, `<a href="${model}" target="_blank">${item}</a>`)
})
document.querySelector('#jsContainer').innerHTML = str
}
}
2.题解
function link() {
var jsContainer = document.getElementById('jsContainer');
var content = jsContainer.innerHTML;
var reg = /(http:\/\/)?(https:\/\/)?www\.[\w=\?&\.#]+/g;
var newContent = content.replace(reg, function ($, $1, $2) {
var url = '';
if ($1 || $2) {
url = $;
} else {
url = 'http://' + $;
}
return '<a href="' + url + '" target="_blank">' + $ + '</a>';
});
jsContainer.innerHTML = newContent;
}