0

I am trying to surround dates in middleRsults with tags:

var middleRsults = "95.00      04/07/15    aaaa  10/02/15 ";
var regex =/\d{2}\/\d{2}\/\d{2}/g;
var x= middleRsults.replace(regex,"<b>$1</b>")

What I want to get:

  95.00      <b>04/07/15</b>    aaaa  <b>10/02/15</b> 

instead, what I actually get:

95.00      <b>$1</b>    aaaa  <b>$1</b> 

I search a lot, but couldn't figure out why this is happening with this specific regex that I am using.

1
  • Read the documentation carefully to learn what $1 means, and what other special replacement patterns are available. Commented Dec 25, 2016 at 16:17

3 Answers 3

3

With your current regular expression you can simply use the matched substring $&:

var middleRsults = '95.00      04/07/15    aaaa  10/02/15 ',
    regex = /\d{2}\/\d{2}\/\d{2}/g,
    x = middleRsults.replace(regex, '<b>$&</b>');

console.log(x);

Or, for more complex situations, you can specify a function as a parameter where match is the matched substring (Corresponds to $& above.):

var middleRsults = '95.00      04/07/15    aaaa  10/02/15 ',
    regex = /\d{2}\/\d{2}\/\d{2}/g,
    x = middleRsults.replace(regex, match => `<b>${match}</b>`);

console.log(x);

Sign up to request clarification or add additional context in comments.

Comments

1

You need a capturing group to use the $n replacement:

var regex =/(\d{2}\/\d{2}\/\d{2})/g;

The parentheses form such a group. The groups are numbered left-to-right in the pattern.

Comments

1

You'll probably face-palm when you realise this but your regex doesn't contain a capture group for $1 to refer to.

This should hopefully fix it:

var regex = /(\d{2}\/\d{2}\/\d{2})/g;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.