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/
3 Answers
Reset to default 5Here'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);
}