JamesEggers
JamesEggers

Reputation: 12935

Handling Multiple JavaScript Replace Matches

I have the following string:

This *is* a *test*!

I want to bold the words surrounded by the * characters (so "is" and "test" in the example).

I have the following JavaScript code:

var data = "This *is* a *test*!";
return data.replace(/\*(.*)\*/g, <b>$1</b>);

When the string is returned, I get the following:

This <b>is* a *test</b>!

How can I change the pattern or basic code in order to do the replacement the way I want it?

Upvotes: 4

Views: 5559

Answers (2)

Bryan Migliorisi
Bryan Migliorisi

Reputation: 9210

SO messed with my HTML...

var result = "This *is* a *test*!".replace(/\*(.*?)\*/gi, "<b>$1</b>");

Upvotes: 5

PatrikAkerstrand
PatrikAkerstrand

Reputation: 45721

You need to make the pattern non-greedy by adding the ?-operator after the *:

var data = "This *is* a *test*!";
return data.replace(/\*(.*?)\*/g, "<b>$1</b>");

Here is a reference for JavaScript RegExp from Mozilla Developer Center.

Upvotes: 2

Related Questions