简体   繁体   中英

Javascript: wrap matched regex with tags

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.

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM