How can i split strings that has prefix and suffix in Javascript?

I have string that is stored in a variable in this form :

var c = "<p>Let's try with single inputs : *[]*</p>"

I can easily split and convert the *[]* into <span> using this method [a]:

var res = c.split("*[]*");
if(res.length > 1){
  var strContent = res[0];
  var inptSoal = ' <span id="content-input" class="al question mb-0">[ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ]</span> ';
  strContent += inptSoal;
  strContent += res[1];

  c = strContent;
} return c;

But now, let’s say that i have this form of string [b] :

var c = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>"

How can i split (and convert) every *[ and ]* (that has strings inside of it) into HTML <span> element? Thanks in advance


To make it clearer, using the method i write above ([a]) it will return this in my website : enter image description here

What i want to do is to return the same result if the condition is like the second form ([b]) i mentioned above. How can i achieve this?


Every answers here solved my problem. The first answer here was Ofek‘s answer. It works well, what i need to do to achieve the result i want is only to change the "<span>" + input + "</span>" inside the replace() function into :

"<span id='content-input' class='al question mb-0'>" + input + "</span>" to make the span element has the CSS Style like my screenshot above.

Other two answers, sid‘s answer and Rahul Kumar‘s answer also works well. But i prefer to choose Rahul Kumar‘s answer for its simplicity.

Thanks in advance to everyone that answered my questions!


Use regex to match the pattern and pass it to String.replace() method to replace the matched pattern in your string with new string <span>$1</span>. Here $1 indicates the captured group which is a content inside brackets *[...]*.

str = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>"
const regex = /*[(.*?)]*/g;
const finalStr = str.replace(regex, "<span>$1</span>");