0

In the string hello, dude <br> how <br> are <br> you <br>

How can I remove the <br> tag at the end if it exists?

Useless Code
  • 12,123
  • 5
  • 35
  • 40
sijo vijayan
  • 1,590
  • 1
  • 21
  • 34

7 Answers7

2
var text = 'hello, dude how < br> are < br> you < br>';
text = text.replace(/< br>$/, '');

Pure javascript.

Advice: Use jquery.

Mattigins
  • 1,014
  • 9
  • 25
  • While I love jQuery, why is your advice to incorporate a whole library for a menial task? Even your example doesn't use it. – Gary Sep 01 '14 at 06:00
  • Yes it is. It would make this whole thing a lot simpler. – Mattigins Sep 01 '14 at 06:00
  • 3
    How does jQuery simplify a basic regex? – Gary Sep 01 '14 at 06:02
  • good, but it doesn't account for if there is an ending slash, like
    though honestly I would not recommend using br so much. You'd be better off using semantic HTML.
    – tomysshadow Sep 01 '14 at 15:31
  • This works better for me: text.replace(/(
    \s*)+$/,'') - taken from http://stackoverflow.com/questions/8056106/how-to-remove-trailing-html-break-from-string
    – Fanky Jul 21 '16 at 20:10
1

try

var str = "how <br> are <br> you <br>";
var s = str.split("<br>");
if (s[s.length - 1].length == 0) {
    s.pop();
    console.log(s.join("<br>"));
}

DEMO

Balachandran
  • 9,567
  • 1
  • 16
  • 26
1

With substring function.

var str = "how <br> are <br> you <br>";
alert(str.substring(0, str.lastIndexOf("<br>"))); // check before if <br> is there in the end.
sijo vijayan
  • 1,590
  • 1
  • 21
  • 34
SK.
  • 4,174
  • 4
  • 30
  • 48
0

I think if the <br/> tag has an side effect on you layout, you can use CSS to hide them.

For example:

br { display: none; }.

If not, you can try answers above.

Kevin Yue
  • 312
  • 2
  • 9
0

You can use javascript alone,

http://www.w3schools.com/jsref/jsref_replace.asp

Or as @Mattigins said, use JQuery like:

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

But I think using jquery just for this task is not appropriate.

Community
  • 1
  • 1
Arman
  • 437
  • 3
  • 19
0
function removeEndBr(string) {
var strSplit = string.split("<br>");
while (strSplit[strSplit.length - 1] == "") {
    strSplit.pop();
}

return strSplit.join("<br>");

}

This function will return the same string but with no <br> in the end. It not only removes the last <br>, but it continues to remove it until there is no <br> in the end.

Osmar
  • 198
  • 9
-1

this is a function for do that!

jQuery:

var text= "how <br> are <br> you <br> my brother";
var items = text.split(" ");

items=f(items,"");
items=items.replace("<br>","");

var items = items.split(" ");

var items=f(items," ");
alert(items);

function f(items,ext){
    var newitem = new Array();
    var j=0;
    for(i=items.length-1;i>=0;i--)
    {
        newitem[j]=items[i]+ext;
        j++;
    }
    items=newitem.join(" ");
    return (items);
}

See Demo on JSFiddle

mostafaznv
  • 958
  • 14
  • 24