首页 > 试题广场 >

替换链接

[编程题]替换链接
  • 热度指数:5014 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
页面中存在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、所有链接在新窗口打开
function link() {
    const el = document.getElementById('jsContainer');
      const reg = /(https?:\/\/[\w\.?]+)|(www\.[\w\.?=&]+)/gim;
      const str = el.innerText
      const res = str.replaceAll(reg, (s) => {
        return `<a href=${s} target=_branks>${s}</a>`
      });
      el.innerHTML = res;
}


发表于 2023-01-19 17:17:57 回复(0)
// 正則不大行,還是要多練練
function link() {
    let jsContainer = document.querySelector("#jsContainer"), jsContainerText = jsContainer.innerText,str = ''
    // 写正则匹配对应的参数
    str = jsContainerText.replace(/((https|http)\:\/\/)?www\.[A-z]+(\.(com|cn))+(\?(\w*=\w*)(\&\w*=\w*)*(\#\w*)*)?/g,function(val){
        let hrefUrl = val
        if(!(/(https|http)/.test(val))) hrefUrl = 'http://' + hrefUrl
        return `<a href="${hrefUrl}" target="_blank">${val}</a>`
    })
    jsContainer.innerHTML = str
}

发表于 2022-07-12 13:59:16 回复(0)
function link() {
    var container = document.getElementById('jsContainer');
    var str = container.innerHTML;
    console.log(str);
    str=str.replace(/(http:\/\/|https:\/\/|www\.)([a-zA-Z0-9._=?#]+)/g,function(el){
        if(/^www/.test(el)){
            return `<a href="http://${el}" target="_blank">${el}</a>`;
        }else{
            return `<a href="${el}" target="_blank">${el}</a>`;
        }
    })
    container.innerHTML = str;
}

发表于 2022-02-17 09:49:49 回复(0)
function link() {
  let node = document.getElementById('jsContainer')
  let res = node.innerText.replace(
    /((?:https?\:\/\/)?www(?:\.[\w]+){2,}(?:\?[\w]+\=[\w]+)?(?:\#\w+)?)/g,
    function (p1) {
      let href = p1.indexOf('http') == -1 ? 'http://' + p1 : p1
      return `<a href="${href}" target="_blank">${p1}</a>`
    }
  )
  node.innerHTML = res
}

发表于 2021-12-05 23:58:24 回复(0)
function link() {
        var dom = document.getElementById('jsContainer')
        dom.innerHTML = dom.innerText.replace(/(http(s)?:\/\/|www\.)[\w\.\?\=\&#%]+/glj => {
            var bl = /^www/
            var c = ''
            bl.test(lj) ? c = 'http://' + lj : c = lj
            return `<a href="${c}" target="_blank">${lj}</a>`
            // return `<a href=" ` +  c  + ` " target="_blank">` +  lj + ` </a>`
        })
    }
第七行代码可以通过,第八行不行???
发表于 2021-07-15 14:14:00 回复(0)