最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to remove the br tag from the end of a string - Stack Overflow

programmeradmin2浏览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?

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?

Share Improve this question edited Sep 1, 2014 at 6:50 Useless Code 12.4k5 gold badges36 silver badges42 bronze badges asked Sep 1, 2014 at 5:51 sijo vijayansijo vijayan 1,7401 gold badge22 silver badges36 bronze badges 5
  • $("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
Add a ment  | 

7 Answers 7

Reset to default 2
var 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);
}

See Demo on JSFiddle

发布评论

评论列表(0)

  1. 暂无评论