2015-12-22 32 views
0

我試圖把與此格式的多個鏈接字符串:JS獲得字符串中多個環節

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 
} 

我覺得這可能是沒找到鏈接的最佳方法,如果有一個更有效的方法I D不要介意完全改變整個事物。

回答

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