JS获取字符串

时间:2015-12-22 00:51:07

标签: javascript regex url hyperlink find

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

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
}

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

1 个答案:

答案 0 :(得分:0)

另一个想法,但不是非常强大,效率低于你的。

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>"