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?
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?
- $("br:last").remove(); would work I think. – VPK Commented Sep 1, 2014 at 5:54
- You need to provide us with that you have tried. – Mattigins Commented Sep 1, 2014 at 5:55
- you want to remove the last br tag or all br tag? – Zeeshan Commented Sep 1, 2014 at 6:02
- What is your expected output??? – Manwal Commented Sep 1, 2014 at 6:03
- Possible duplicate of how to remove trailing html break from string? – Fanky Commented Jul 21, 2016 at 20:11
7 Answers
Reset to default 2var text = 'hello, dude how < br> are < br> you < br>';
text = text.replace(/< br>$/, '');
Pure javascript.
Advice: Use jquery.
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.
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
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.
You can use javascript alone,
http://www.w3schools./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.
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.
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);
}