views:

58

answers:

2

I'm doing some in browser editing, and I have some content that's on the order of around 20k characters long in a <textarea>.

So it looks something like:

<textarea>
Text 1
Text 2

Text 3
Text 4
[...]
Text 20,000
</textarea>

I'd like to use jquery to trim it down when someone hits a button to chop, but I'm having trouble doing it without overloading the browser. Assume I know that the character numbers are at 16,510 - 17,888, and what I'd like to do is trim it.

I was using:

jQuery('#textsection').html(jQuery('textarea').html().substr(range.start));

But browsers seem to enjoy crashing when I do this. Alternatives?

EDIT

Solution from the comments:

 var removeTextNode = document.getElementById('textarea').firstChild;
 removeTextNode.splitText(indexOfCharacterToRemoveEverythingBefore);
 removeTextNode.parentNode.removeChild(removeTextNode);
+1  A: 

What browser are you testing on?

substr takes the starting index, and an optional length. If the length is omitted, then it extracts upto the end of the string. substring takes the starting and ending index of the string to extract, which I think might be a better option since you already have those available.

I've created a small example at fiddle using the book Alice's Adventures in Wonderland, by Lewis Carroll. The book is about 160,000 characters in length, and you can try with various starting/ending indexes and see if it crashes the browser. Seems to work fine on my Chrome, Firefox, and Safari. Unfortunately I don't have access to IE. Here's the function that's used:

function chop(start, end) {
    var trimmedText = $('#preId').html().substring(start, end);
    $('textarea').val(trimmedText);
}
​
Anurag
Very thorough and quick answer! I'm using FF 3.6 - let me try exactly what you're doing and see if i can repro. Every time I do it, it whites out the browser.
aronchick
thanks. an infinite loop somewhere might be causing the browser to crash, or maybe some other processing is triggered when you click trim.
Anurag
+2  A: 

Not sure about jQuery, but with plain vanilla Javascript, this can be done by using the splitText() method of the textNode object. Your <pre> has a textNode child which contains all the text inside of it. (You can get it from the childNodes collection.) Split it at the desired index, then use removeChild() to delete the part you don't need.

levik
Very interesting!Actually, i made a mistake above - it's a textarea... would this still work?
aronchick
Worked perfectly! Adding code to the question.
aronchick
BTW, your last line can be simplified to save one doc ID lookup: removeTextNode.parentNode.removeChild(removeTextNode)
levik