dharanbro
dharanbro

Reputation: 1342

JS Slice() doesn't work properly

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.

update

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

Answers (3)

Hoyen
Hoyen

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

andi
andi

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

bugwheels94
bugwheels94

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);

Working demo

Upvotes: 1

Related Questions