I have some script which makes replacements. It works fine, but because of replaced values standing close to each other i’ve got more than one
between values.
It looks like:
<br />
Value
<br />
Value
<br />
<br />
Value
<br />
Value
<br />
<br />
Value
<br />
<br />
<br />
My task is to get only one <br>
between values:
<br />
Value
<br />
Value
<br />
Value
Because of not so many variations in my list I know one decision for all available variants but it is bad hardcode something like:
var mystring=`<br />
<br />`
for (i=0; i<mystring.length; i++){
var regex = new RegExp(mystring[i],"g");
mystring = mystring.replace(regex, "");
}
Is there any elegant way to solve my case? Thinking of regexp but it’s too hard for me to write it. Or may be there is another way?
5
If you add then to the DOM, you can (reverse) loop over the children, and remove any duplicate element.
Might want to extend this to capture the first/last one.
The below results in
<br>
<em>Hello!</em>
<br>
<em>Hello!</em>
<br>
<em>Hello!</em>
<br>
<em>Hello!</em>
<br>
<em>Hello!</em>
<br>
const cs = document.body.children;
for (let i = cs.length - 1; i > 0; i--) {
current = cs[i];
before = cs[i - 1];
if (current.nodeName === before.nodeName) {
current.remove();
console.log(`Removing child #${i}:`, current)
}
}
<br />
<em>Hello!</em>
<br />
<em>Hello!</em>
<br />
<br />
<em>Hello!</em>
<br />
<em>Hello!</em>
<br />
<br />
<em>Hello!</em>
<br />
<br />
<br />
1