用Javascript/jQuery中的正则表达式替换模式的所有实例 [英] Replace all instances of a pattern with regular expressions in Javascript / jQuery

查看:90
本文介绍了用Javascript/jQuery中的正则表达式替换模式的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我对正则表达式不太了解,需要购买一本书,因为这对我来说很难买到.

First off I don't know much about regex and need to buy a book because it's has proven to me to be difficult to pickup.

最终,我想使用一个dom元素,并在直括号"["和]"中替换文本,并在文本周围插入一个链接,并且字符串中可能有多个括号集.

Ultimately I want to take a dom element, and replace text within straight brackets "[" and "]" and insert a link around the text, and there may be multiple bracket sets in the string.

function changeTip() {  
        var link = '<a href="' + $('#txtURL').attr('value') + '" target="_blank">';
        $('.tipoftheweektip').html($('#txtTip').attr("value").replace('[', link).replace(']', '</a>'));
    }

这有效,除了:

  • 不使用第二组括号
  • 如果没有右括号,它将删除右括号之前的所有文本

我看过示例,并且由于正则表达式代码中使用了方括号,因此我无法弄清楚如何查找和替换方括号.

I've looked at examples and because straight brackets are used in the regex code, I cant figure out how to look for a bracket and replace it.

有人在做类似的事情,他们可以分享吗?预先感谢.

Anyone out there that has done something similar that they can share? Thanks in advance.

推荐答案

.replace(/\[([^\]]*)\]/g, link + "$1</a>")

的意思是,在[和]之间找到文本,并将其替换为link的值,文本本身和''.这样可以确保匹配的方括号. "g"表示多次(全局)执行".

which means, find text between [ and ] and replace it with the value of link, the text itself and ''. This ensures matching square brackets. The 'g' means 'do it multiple times (globally)'.

这篇关于用Javascript/jQuery中的正则表达式替换模式的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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