题解 | #替换链接#
替换链接
http://www.nowcoder.com/practice/4578a70b955848ff8e95c1f88c94c1ba
解题思路
此题最大的难点在于不支持正则表达式的负向先行断言
导致前面不匹配 / 很难实现
/(?<!\/)(www\.[\w\.\?\&\=%#]+) ?/g
最终只能在replace方法里面判断
(t, matchText, index, all) => {
if (index > 0 && all[index - 1] === "/") return matchText;
return (
'<a href="http://' +
matchText +
'" target="_blank">' +
matchText +
"</a>"
);
} 最终代码
function link() {
const el = document.getElementById("jsContainer");
const content = el.textContent;
const re = /(https?\:\/\/[\w\.\?\&\=%#]+) ?/g;
let result = content
.replace(re, '<a href="$1" target="_blank">$1</a>')
.replace(
// /(?<!\/)(www\.[\w\.\?\&\=%#]+) ?/g,
// '<a href="http://$1" target="_blank">$1</a>'
/(www\.[\w\.\?\&\=%#]+) ?/g,
(t, matchText, index, all) => {
if (index > 0 && all[index - 1] === "/") return matchText;
return (
'<a href="http://' +
matchText +
'" target="_blank">' +
matchText +
"</a>"
);
}
);
el.innerHTML = result;
} 优化点可以把两个 replace 合并成一个
在替换的方法里面判断前面是 http 或者 https
心累,不支持也没有报错,只能一行行试,跟个瞎子一样
查看1道真题和解析