【问题标题】:JS Get multiple links in a stringJS 获取字符串中的多个链接
【发布时间】:2016-03-28 04:28:42
【问题描述】:

我正在尝试使用如下格式的多个链接转换字符串:

random text and a link: [Google](http://google.com),
also check out this link: [Facebook](http://facebook.com)
which can all be found here: http://example.com

进入这个:

random text and a link: <a href="http://google.com">Google</a>,
also check out this link: <a href="http://facebook.com">Facebook</a>
which can all be found here: <a href="http://example.com">http://example.com</a>

现在我有一个只能找到第一个链接的功能

function findURL(comment) {
    //Find text in round brackets
    var roundBrackets = /\(([^)]+)\)/
    var matches = roundBrackets.exec(comment)

    if(matches != null && matches[1] != undefined && ~matches[1].indexOf("http")){
      //If found link in round brackets, see if it's accompanied by text in square brackets
      var squareBrackets = /\[([^)]+)\]/
      var text = squareBrackets.exec(comment)
      var linkText = matches[1] //Will be overwritten if there is text in square brackets

      if(text != null){
        linkText = text[1]
        comment = comment.replace(text[0], '')
      }

      var link = '<a href="'+matches[1]+'">'+linkText+'</a>'
      comment = comment.replace(matches[0], link)
    }
    //Find regular links
    else if(comment && ~comment.indexOf("http")){
      var urlRegex = /(https?:\/\/[^\s]+)/g
      var url = urlRegex.exec(comment)
      var newLink = '<a href="'+url[1]+'">'+url[1]+'</a>'
      comment = comment.replace(url[1], newLink)
    }
  return comment
}

我觉得这可能不是查找链接的最佳方法,如果有更有效的方法我不介意完全改变整个事情。

【问题讨论】:

    标签: javascript regex url hyperlink find


    【解决方案1】:

    另一个想法,但并不比你的更强大和效率更低。

    var r = "random text and a link: [Google](http://google.com),
    also check out this link: [Facebook](http://facebook.com) 
    which can all be found here: http://example.com";
    
    var o = r.match(new RegExp(/(\[[\w\-\.]+\]+)(\(?http:[\/\w\-\.]+\))|(http:[\/\w\-\.]+)/g));
    var v = r;
    for(i in o)
    {
        if(o[i].indexOf("]") >= 0)
        {
           var p = o[i].replace(/[\[\]\(\)]/g, ' ').trim().split(' ');
           v = v.replace(o[i], "<a href='"+p.pop()+"'>"+p.shift()+"</a>");
        }else
        {
           v = v.replace(o[i], "<a href='"+o[i]+"'>"+o[i]+"</a>");
        }
    }
    

    输出

    "random text and a link: <a href='http://google.com'>Google</a>,
    also check out this link: <a href='http://facebook.com'>Facebook</a> 
    which can all be found here: <a href='http://example.com'>http://example.com</a>"
    

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 2021-03-11
      • 2016-02-13
      • 2017-08-28
      相关资源
      最近更新 更多