开发者

Recommendations on Triming Large Amounts of Text from a DOM Object

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.开发者_StackOverflow 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);


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.


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);
}
​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜