简体   繁体   中英

Replace Square Brackets for links on web page

I'm trying to do a parse of html content using jQuery/Javascript. I want to look for words between square brackets and change the whole word for a link.

Example:

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

I'm trying to use Regular Expressions to change what's inside the double brackets into something like this:

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

I can find all instances of words between square brackets with this regex:

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

But don't know how to replace the text.

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

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

Something like:

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

should work.

But you should hava a look to _.template method !.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM