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

javascript - Remove first and last <br > from string - Stack Overflow

programmeradmin1浏览0评论

I have this html code :

<p id="demo">Visit <br /> stackoverflow <br /> or jsfiddle <br /></p>
<button onclick="myFunction()">Try it</button>
function myFunction()
{
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace("<br />","");
    document.getElementById("demo").innerHTML=res;
}

I want to remove first and last <br /> from it not all of them.
this is my jsfiddle /

I have this html code :

<p id="demo">Visit <br /> stackoverflow <br /> or jsfiddle <br /></p>
<button onclick="myFunction()">Try it</button>
function myFunction()
{
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace("<br />","");
    document.getElementById("demo").innerHTML=res;
}

I want to remove first and last <br /> from it not all of them.
this is my jsfiddle http://jsfiddle/3W83m/

Share Improve this question edited Nov 26, 2013 at 20:27 PSL 124k21 gold badges256 silver badges243 bronze badges asked Nov 26, 2013 at 20:10 Adam Mo.Adam Mo. 7722 gold badges12 silver badges26 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Here's a solution to the general problem you ask:

var arr = str.split(/<br\s*\/?>/);
var res = arr[0]+arr.slice(1,-1).join('<br>')+arr.slice(-1);

This answer doesn't require the first and last child to be <br>.

If you just want to remove <br> at the ends, then it's easy :

var res = str.replace(/^\s*<br\s*\/?>|<br\s*\/?>\s*$/g,'');

Demonstration

You can try this way, if you are sure that first and last element child are br: Other wise you can loop through to test for the first and last br and remove them.

function myFunction() {
    var elem= document.getElementById("demo");
    elem.removeChild(elem.firstElementChild);
    elem.removeChild(elem.lastElementChild);
}

Demo

To ensure it removes only fist and last brs and not any other element if first/last one is not a BR, you can add a simple check for safety.

function myFunction() {
    var elem= document.getElementById("demo"), 
        fChild = elem.firstElementChild, 
        lChild =elem.lastElementChild;

if(fChild.tagName === "BR")
    elem.removeChild(fChild);
if(lChild.tagName === "BR")
    elem.removeChild(lChild);

}

first <br/>:

if (myString.indexOf('<br/>') > 0) {
  myString = myString.slice(myString.indexOf('<br/>')+5, myString.length);
}

last <br/>:

if (myString.lastIndexOf('<br/>') == myString.length - 5) {
  myString = myString.slice(0, -4);
}
发布评论

评论列表(0)

  1. 暂无评论