替换方括号以获取网页上的链接

时间:2013-02-13 22:18:59

标签: javascript jquery html

我正在尝试使用jQuery / Javascript对html内容进行解析。我想在方括号之间查找单词并更改整个单词以获取链接。

示例:

<div>
   This is text inside a div. It has a reference to an [[Article]]
</div>

我正在尝试使用正则表达式将双括号内的内容更改为:

<div>
   This is text inside a div. It has a reference to an <a href='/dictionary#Article'>Article</a>
</div>

我可以在这个正则表达式的方括号中找到所有单词实例:

$('article').html().match(/[^[\]]+(?=])/g)

但不知道如何替换文字。

2 个答案:

答案 0 :(得分:3)

$("div").html(function(i, html) {
    return html.replace(/\[\[(.+?)\]\]/g, "<a href='/dictionary#$1'>$1</a>");
});

DEMO: http://jsfiddle.net/y4N6e/

答案 1 :(得分:0)

类似的东西:

$('div').html($('div').html().replace(/\[\[([^\]]+)\]\]/, '<a href="/dictionary#$1">$1</a>')

应该有用。

但你应该看看_.template method