RegEx将格式化链接转换为html <a> tag

时间:2017-01-04 23:20:38

标签: javascript regex

Because of some poor forward thinking when building my search database, I'm left with some links in the format of: (Google Homepage)[http://google.com]

I've been trying to mess with regex in Javascript to convert the format above into a regular HTML link in the format of<a href="http://google.com">Google Homepage</a>.

I've been able to pick out the parentheses and brackets via regex, but am having trouble getting regex to replace the parenthesis and brackets with HTML as appropriate. Thanks!

3 个答案:

答案 0 :(得分:3)

这将非常简单。基本上,只需制作两个捕获组。一个捕获组将在括号内包含文本,另一个将在方括号内具有URL。

\((.*?)\)\[(.*?)\]
   #1       #2

然后,您可以简单地将每个捕获的部分粘贴到您的标记中,如下所示:

<a href="\2">\1</a>

Here is a demo

答案 1 :(得分:1)

这对我有用

&#13;
&#13;
var str1="(Google Homepage)[http://google.com]";
    
var pattern=/\((.*)\)\[(.*)\]/;

var str2=str1.replace(pattern,"<a href=\"$2\">$1</a>");

console.log(str2);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

考虑到() [] 定义边界,你可以试试

\(([^\)]+)\).*\[([^\]]+)\]

\ 1将是文本而\ 2将是链接