uksz uksz - 2 months ago 5
Javascript Question

How to change multiple string occurances into one?

I have a string that I receive from backend, like this:

Hello wolrd <br> <br> <br> I am <br><br> Uksz <br>.


Now, the amount of
<br>
is never constant - there can be one, or up to 5. How can I change all
<br>
that are next to each other with only one
<br>
? So that the above example would be:

Hello wolrd <br> I am <br> Uksz <br>.

Answer

you can use this solution:

var test = "Hello wolrd <br><br> <br> <br> <br> <br><br> I am <br><br> Uksz <br><br> <br><br> <br> <br> <br><br> <br> <br> <br><br><br>.";
var re = /(\<br\>)(\s*(\<br\>))+/gi;
var result = test.replace(re, "<br>");
console.log(result);

Comments