How do I use JavaScript to detect
to become one
?
I trie
Wouldn't something like this be the right approach:
$("br~br").remove()
EDIT: No, it's wrong, because its definition of "contiguous" is too loose, as per BoltClock.
Simpler:
var newText = oldText.replace(/(<br\s*\/?>){3,}/gi, '<br>');
This will allow optional tag terminator (/>) and also spaces before tag end (e.g. <br />
or <br >
).
A lot of the other answers to this question will only replace up to certain amount of elements, or use complex loops. I came up with a simple regex that can be used to replace any number of <br>
tags with a single tag. This works with multiple instances of multiple tags in a string.
/(<br>*)+/g
To implement this in JavaScript, you can use the String.replace
method:
myString.replace(/(<br>*)+/g, "<br/>");
To replace multiple <br/>
tags, add a /
to the regex:
/(<br\/>*)+/g