替换方括号以获取网页上的链接 [英] Replace Square Brackets for links on web page

查看:90
本文介绍了替换方括号以获取网页上的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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)

但是不知道如何替换文本.

解决方案

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

演示: http://jsfiddle.net/y4N6e/

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/

这篇关于替换方括号以获取网页上的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆