David R
David R

Reputation: 15667

Leading and Trailing <br> removal

I have string expression like

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

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

Upvotes: 3

Views: 3013

Answers (4)

user663031
user663031

Reputation:

Instead of trying to process HTML with regexps, which is never a good idea even when it seems innocuous, consider neutralizing the br tags with CSS.

br { display: none; }

See Ignore <br> with CSS?.

If you want to compress multiple br tags, then

br + br { display: none; }

In your particular case, CSS has no way to detect if the br's appear at the beginning or end of the element. So here's a bit of JavaScript. In general, it's better to manipulate the DOM like this using DOM APIs, instead of mucking around with regexps on 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're a stickler for 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');
}

Upvotes: 3

falsetru
falsetru

Reputation: 369334

You can use the following regular expression:

/^\s*<br\s*\/?\s*>|<br\s*\/?\s*>\s*$/ig

replace it with empty string:

'   <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 occurrence:

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

Upvotes: 2

Sam
Sam

Reputation: 20486

If performed globally, this will match all the leading line breaks and all the trailing line breaks (as well as whitespace before/after, let me know if you want to keep the leading/trailing whitespace):

^\s*(?:<br\s*\/?\s*>)+|(?:<br\s*\/?\s*>)+\s*$

Use it like so:

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>

Upvotes: 3

David R
David R

Reputation: 15667

I've managed to arrive at solution finally. Below is the RegEx which is working for me.

    /^[<br>]*\s*[<br>]*|[<br>]*$/g 

Thanks for all the help!

Upvotes: -4

Related Questions