1

I'm trying to replace a string between strings, and it to happen multiple times.

Currently, my code is

var str = `**Bolded text**`
var re = new RegExp(/\*\*(.*)\*\*/gi)
let newStr = str.replace(re, "<b>$1</b>")
console.log(newStr);

That example works fine and returns this:

<b>Bolded text</b>

However, if I try adding multiple **texts** in the string, it does it incorrect

var str = `**Bolded text 1** **Bolded text 2**`

It returns

<b>Bolded text 1** **Bolded text 2</b>

And I want it to return

<b>Bolded text 1</b> <b>Bolded text 2</b>

How would I go about doing this?

Martin
  • 25
  • 3

1 Answers1

3

Regex greedy problem, you need to add the question mark here /\*\*(.*?)\*\*/gi

https://regex101.com/r/c8bwEg/1

Greedy will consume as much as possible.

var str = `**Bolded text 1** **Bolded text 2**`
var re = new RegExp(/\*\*(.*?)\*\*/gi)
let newStr = str.replace(re, "<b>$1</b>")
console.log(newStr);
Ele
  • 33,468
  • 7
  • 37
  • 75