最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript replace() and $1 issue - Stack Overflow

programmeradmin5浏览0评论

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>");
    });
});

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?

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>");
    });
});

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?

Share Improve this question asked Nov 13, 2012 at 21:14 ShintoTunaShintoTuna 3,7878 gold badges30 silver badges36 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 11

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.

Another option is to use $&, which stands for the whole match (also $0 in other flavors):

html.replace(/E[0-9]{3,4}/g, "<strong>$&</strong>");

I'd also remend the jQuery Highlight Plugin - You might be able to adapt it to use a regex, the code is pretty straightforward.

Wrap the group you want to capture in brackets:

/(E[0-9]{3,4})/g
发布评论

评论列表(0)

  1. 暂无评论