题解 | #替换链接#

替换链接

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
心累,不支持也没有报错,只能一行行试,跟个瞎子一样

全部评论

相关推荐

鼠鼠第一次实习,啥也不懂一直是自己一个人吃的饭,不会做工作老是被嫌弃,大人的世界是这样的吗?
我是星星我会发亮:好的mt有两种,一种愿意教你的,一种几乎什么活都不给你派让你很闲允许你做自己事情的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务