sijo vijayan
sijo vijayan

Reputation: 1710

How to remove the br tag from the end of a string

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?

Upvotes: 0

Views: 8288

Answers (7)

Osmar
Osmar

Reputation: 306

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.

Upvotes: 0

SK.
SK.

Reputation: 4358

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.

Upvotes: 1

mostafaznv
mostafaznv

Reputation: 988

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

Upvotes: -1

Arman
Arman

Reputation: 467

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.

Upvotes: 0

Kevin Yue
Kevin Yue

Reputation: 392

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.

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

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

Upvotes: 1

Mattigins
Mattigins

Reputation: 1016

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

Pure javascript.

Advice: Use jquery.

Upvotes: 2

Related Questions