Leading and trailing delete

I have a string expression like

<br /><br /><br/ >this is <br /><br /><br/ > a test<br /><br /><br/ ><br> 


in which I only need to remove the first and last set of tags <br />

using simple javascript.


source to share

4 answers

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):



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

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

Run codeHide result



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) {




You can use the following regex:



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/ >"



To remove multiple cases:



'   <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"




I finally managed to come to a solution. Below is the RegEx that works for me.



Thanks for the help!



All Articles