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?

1 Answer 1

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

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

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.