Javascript replace()和$ 1问题 [英] Javascript replace() and $1 issue

查看:247
本文介绍了Javascript replace()和$ 1问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个脚本,该脚本在文本中搜索模式并在其找到的字符串周围包装标记。

I am trying to create a script that searches for a pattern in text and wrap a tag around the string it finds.

$(".shop_attributes td").each(function () {
    $(this).html(function(i, html) {
        return html.replace(/E[0-9]{3,4}/g, "<strong>$1</strong>");
    });
});

这是我使用的代码,它确实找到了我正在寻找的但它实际上做的是生成一个内部$ 1的标签。我期望它做的是将它找到的字符串放入强标签。我在这里做错了什么?

this is the code i use and it does find what i'm looking but what it actually does is produce a tag with $1 inside. What i expect it to do is to put the string it found into strong tags. What am i doing wrong here?

推荐答案

您需要先捕捉匹配,然后才能使用它。使用括号:

You need to capture the match, before you can use it. Use parentheses:

$(".shop_attributes td").each(function () {
    $(this).html(function(i, html) {
        return html.replace(/(E[0-9]{3,4})/g, "<strong>$1</strong>");
    });
});

Ridiculously over -simplified JS Fiddle demo

这篇关于Javascript replace()和$ 1问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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