Leading and trailing delete
If you execute globally, this will match all leading line breaks and all line breaks (just like before / after whitespace, let me know if you want to keep leading / trailing whitespace):
^\s*(?:<br\s*\/?\s*>)+|(?:<br\s*\/?\s*>)+\s*$
Use it like this:
var regex = /^\s*(?:<br\s*\/?\s*>)+|(?:<br\s*\/?\s*>)+\s*$/gi,
string = ' <br /><br /><br/ >this is <br /><br /><br/ > a test<br /><br /><br/ ><br> ';
string = string.replace(regex, ''); //changed replacement
console.log(string);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
source to share
Instead of trying to handle HTML with regular expressions, which is never a good idea, even if it seems harmless, consider neutralizing your tags br
with CSS.
br { display: none; }
See Ignore <br> with CSS? ...
If you want to compress multiple tags br
, then
br + br { display: none; }
In your particular case, CSS has no way of detecting whether it appears br
at the beginning or end of an element. So here's some JavaScript. In general, it's better to manipulate the DOM like this using the DOM API, instead of looping through regular expressions in the string representation of the DOM:
function removeLeadingTrailingBRs(elt) {
var node;
while (node=elt.querySelector('br:first-child')) { elt.deleteChild(node); }
while (node=elt.querySelector('br:last-child')) { elt.deleteChild(node); }
}
Or, if you are a fan of factoring:
function deleteBySelector(elt, selector) {
var node;
while (node=elt.querySelector(selector)) { elt.deleteChild(node); }
}
function remoteLeadingTrailingBRs(elt) {
deleteBySelector('br:first-child');
deleteBySelector('br:last-child');
}
You can use the following regex:
/^\s*<br\s*\/?\s*>|<br\s*\/?\s*>\s*$/ig
replace it with an empty line:
' <br /><br /><br/ >this is <br /><br /><br/ > a test<br /><br /><br/ ><br> '.replace(/^\s*<br\s*\/?\s*>|<br\s*\/?\s*>\s*$/ig, '')
// => "<br /><br/ >this is <br /><br /><br/ > a test<br /><br /><br/ >"
UPDATE
To remove multiple cases:
/^\s*(<br\s*\/?\s*>)+|(<br\s*\/?\s*>)+\s*$/ig
' <br /><br /><br/ >this is <br /><br /><br/ > a test<br /><br /><br/ ><br> '.replace(/^\s*(<br\s*\/?\s*>)+|(<br\s*\/?\s*>)+\s*$/ig, '')
// => "this is <br /><br /><br/ > a test"
source to share