In InDesign, text object references are based on the index of the object from the beginning of the story, and text object collections can change as you add, delete, or format text. For this reason, it's best to use reverse iteration when you're working with text object collections.
I'm not getting the same result as you are--when I try it, the contents of the first text style range get replaced with the new text and retain the formatting of the original text (i.e., the number of text style ranges in the text frame stays the same). But this could be because of differences in our text--presence or absence of return characters, the formatting applied to space characters between the text style ranges, etc.
Here's what I think is going on in your example. When you change the contents of text style range 0, InDesign removes all of the text in that style range, which sets the formatting of the first insertion point in the text to the formatting of the following text style range. That formatting is then applied to the new text you enter by setting the contents. The textStyleRanges collection changes because the text frame now contains only three text style ranges, rather than four.
To change only the text in the first text style range, try something like this:
//Given a text frame "textFrame"...
var textStyleRanges = textFrame.textStyleRanges;
var startCharacter = textStyleRanges.item(0).characters.item(0).index;
var endCharacter = textStyleRanges.item(0).characters.item(-1).index;
textStyleRanges.item(0).insertionPoints.item(-1).contents = "New text";
This enters the new text at the end of the text style range, then deletes the original content of the text style range.
First of all thank you for the answer. Tomorrow I will try your solution. Yes you are right this problems happens only when some times, in particular it happens only when the two textRanges differs only in the paragraph style(ex. paragraph alignment, or identation). For today I found a temporany solution:
I remove all chars of the first stylerange except the last char, then I insert the new text. It seems to work for now but I think it's not the perfect solution. here it is:
while(style.characters.length>1)//note 1 here for last char
this seems to respect styles, but I think it's not the best solution.Your solution seems to be more clever, I will try it tomorow.
Thank you again