-4

I want to replace the multiple <br /> tags with single <br /> using JavaScript in a text. my text like:

some text.<br />
<br />
<br />
<br />
<br />
<br />
<br />
some text

I tried this code:

document.body.innerHTML = document.body.innerHTML.replace(/<br /> <br />
    <br /> <br /><br /> <br />/g,"<br />"); </script>

but it did not work .

10
  • So what JavaScript have you tried so far? Commented Jan 23, 2015 at 15:33
  • stackoverflow.com/questions/1137436/… Commented Jan 23, 2015 at 15:33
  • I tried this code: document.body.innerHTML = document.body.innerHTML.replace(/<br /> <br /> <br /> <br /> <br /> <br />/g,"<br />"); </script> but it did not work Commented Jan 23, 2015 at 15:34
  • 2
    Do you want to replace occurences of "<br />" in a string, or <br /> elements in the DOM? Commented Jan 23, 2015 at 15:34
  • 2
    @AhmedElshorbagy: To improve your question, use the "edit" link, not comments. Commented Jan 23, 2015 at 15:34

4 Answers 4

7

You have specified that it's in document.body, so in the DOM. Then you can (and you should) use DOM methods:

var siblingBrs = [].slice.call( document.querySelectorAll('br + br') );
siblingBrs.forEach( function( br ){
    br.parentNode.removeChild( br );
});

http://jsfiddle.net/jL8jkkt0/

Notice it's agnostic to the string representation of a <br /> element in the source code.

BTW if it's only for display purposes (to avoid visual gap) you can just use CSS:

br + br { display:none; }

http://jsfiddle.net/jL8jkkt0/1/

Sign up to request clarification or add additional context in comments.

Comments

1

First get the HTML as string then replace it using regex:

var s = document.body.innerHTML;
document.body.innerHTML = s.replace(/(\<br[\s]*\/?\>[\s]*)+/g, '<br/>');
First Line<br><br /><br/><br><br /><br/>Second Line

1 Comment

recommending regex to manipulate HTML is a poor advice stackoverflow.com/a/1732454/4879
0

Try the following:

var stripped = original.replace(/(<br\s*\/?>){3,}/gi, '<br>');

Substituting different values here...

{3,}

...will allow you to control at what count the removal occurs.

Hope this helps!

Comments

-1

Try this :

var newText = oldText.replace(/(<br\s*\/?>){3,}/gi, '<br>');

working fiddle:

http://jsfiddle.net/r5bu1xq2/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.