Pier
Pier

Reputation: 10827

Regex match and replace with delimiters included in JS

How can I match and replace some pattern but include the delimiters in my match?

I'd like to add a <strong> HTML tag around the these two delimiters $ and USD.

From this

"Buy today for $ 100 USD"

To this

"Buy today for <strong>$ 100 USD</strong>"

The price could be either 100, 100.99, or even 1,000.99.

I'm trying this but it doesn't work.

someString.replace(/(\$)(.*?)(USD)/, '<strong>$1</strong>');

Upvotes: 0

Views: 72

Answers (2)

Mr_Green
Mr_Green

Reputation: 41832

You can also use a function to return the replace

someString.replace(/(\$[ ]?[\d\.\,]+[ ]?USD)/, 
          function(x){
              return '<strong>' + x + '</strong>';
          }
);

Upvotes: 1

hwnd
hwnd

Reputation: 70732

Simply place the delimiters inside of the main capturing group instead of separating them into three groups.

var r = 'Buy today for $ 100 USD'.replace(/(\$.*?USD)/, '<strong>$1</strong>')
console.log(r); //=> "Buy today for <strong>$ 100 USD</strong>"

Upvotes: 4

Related Questions