JavaScript Multiple Matching

I have the following line:

This *is* a *test*! 

I want bold words surrounded by * 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 returns, I get the following:

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

How to change the template or base code to make the replacement the way I want?

+4
source share
2 answers

SO messed with my HTML ...

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

Do you need to make the template not greedy by adding? -operator after *:

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

Here is the link for JavaScript RegExp from the Mozilla Developer Center .

+2
source

Source: https://habr.com/ru/post/1286382/


All Articles