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?
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 recommend 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With