Reputation: 1342
I am trying to remove the last characters from the following html code
<tbody><tr><tr>1<td><label for='depart1'>Department 1</label><br /><input type='text' id='depart1' class='textbox large' value='IT' /><br><label for='Courses_for_depart1'>Course for Department 1</label><br /><textarea id='Courses_for_depart1' class='textarea large' >OS</textarea></td></tr></tbody>
with the following code
addHtml.slice(0,-13);
It should remove </tr></tbody>
But it removes only ></tbody>
how to get rid of this strange behavior.
addHtml=$("#departments").html();
<table id="departments">
<tbody><tr><tr>1<td><label for='depart1'>Department 1</label><br /><input type='text' id='depart1' class='textbox large' value='IT' /><br><label for='Courses_for_depart1'>Course for Department 1</label><br /><textarea id='Courses_for_depart1' class='textarea large' >OS</textarea></td></tr></tbody> </table>
The above snippet is copied form view source code of chrome.
Upvotes: 2
Views: 1082
Reputation: 2519
There are probably white space between the closing </tbody>
tag and the </tr>
tag. Try something like this:
addHtml = addHtml.trim();
var tbody = '</tbody>';
var t1 = addHtml.indexOf(tbody)+tbody.length;
var t2 = addHtml.lastIndexOf('</tr>');
var len = t1-t2;
var newString = addHtml.slice(0,-len); // This will have the string without the </tr> </tbody>
Upvotes: 1
Reputation: 6522
As a possibly safer alternative, you could do this in two steps:
1) find the last </tbody>
in the string, then slice up to it.
2) find the last </tr>
in the remaining string, then slice up to that.
String.prototype.lastIndexOf()
Upvotes: 1
Reputation: 31920
Since your addHTML contains spaces at the end and the beginning, so you need to trim all the spaces at start and end before using slice function so use
$.trim(addHtml).slice(0,-13);
Upvotes: 1