Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace() and $1 issue

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?

like image 340
Nick Avatar asked Nov 13 '12 21:11

Nick


3 Answers

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.

like image 120
David Thomas Avatar answered Oct 16 '22 11:10

David Thomas


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 recommend the jQuery Highlight Plugin - You might be able to adapt it to use a regex, the code is pretty straightforward.

like image 4
Kobi Avatar answered Oct 16 '22 13:10

Kobi


Wrap the group you want to capture in brackets:

/(E[0-9]{3,4})/g
like image 1
Matt Burland Avatar answered Oct 16 '22 11:10

Matt Burland