Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


EDIT

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?


SOLVED

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!

like image 702
Dhimas Yoga Avatar asked Apr 17 '26 16:04

Dhimas Yoga


1 Answers

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>");
console.log(finalStr);
like image 166
Rahul Kumar Avatar answered Apr 20 '26 04:04

Rahul Kumar