如何获取插入字符的位置?比如:
var txt = 'This is some sample text. Select this text.'  ;
var ins = "AAA"把 AAA 插入 txt 后
var txt_ins = 'This is AAA some sample text. Select this text.'  ;
 这第一次插入很容易计算位置 indexOf即可
但是再次插入,如何计算新插入的AAA的位置呢?
var txt_ins = 'This is AAA some AAA sample text. Select this text.'  ;
 var txt_ins = 'This AAA is AAA some AAA sample text. Select this text.'  ;
 

解决方案 »

  1.   

    这个问题的难度在于再次插入 AAA 后,原字符串中的 AAA 的位置变了,不好比较.var txt_ins第一次 = 'This is AAA some sample text. Select this text.'  ;
    var txt_ins第二次向后 = 'This is AAA some AAA sample text. Select this text.'  ;
    var txt_ins第三次向后 = 'This is AAA some AAA sample AAA text. Select this text.'  ;和var txt_ins第一次 = 'This is AAA some sample text. Select this text.'  ;
    var txt_ins第二次向前 = 'This AAA is AAA some sample text. Select this text.'  ;
    var txt_ins第三次向前 = 'AAA This AAA is AAA some sample text. Select this text.'  ;处理起来的规律不一样,很难找出.
      

  2.   

    没规律怎么弄啊 lastIndexOf找出最后插入的AAA再往后插?
      

  3.   

    楼主是想找到最新一次插入的内容的位置是吧?大概写了个。。有个小bug就是如果插入的内容中间没有其他的内容分隔会找不到正确的位置。明天了再看看。。function getNewInsertIndex(oldArray,newArray){
      if(oldArray.length==newArray.length)alert('没有找到或者插入新内容!');
      else{
        var index=0;
        for(var i=0,j=newArray.length;i<j;i++){
          index+=newArray[i].length
          if(newArray[i]!=oldArray[i]){index+=i*ins.length;/*加上分隔字符长度*/ alert('新插入的内容位置为'+index);break;}
        }
      }
    }
    var txt = 'This is some sample text. Select this text.'  ;
    var ins = "AAA "
    var txt_ins = 'This is AAA some sample text. Select this text.'  ;
    var arr=[],newarr=txt_ins.split(ins);
    getNewInsertIndex(arr,newarr);
    arr=newarr;//交换位置,每次更新过内容后记得交换位置txt_ins ='This AAA is AAA some sample text. Select this text.'  ;
    newarr=txt_ins.split(ins)
    getNewInsertIndex(arr,newarr)
    arr=newarr;//txt_ins ='AAA This AAA is AAA some sample text. Select this text.' 
    newarr=txt_ins.split(ins)
    getNewInsertIndex(arr,newarr)
    arr=newarr;//txt_ins ='AAA This AAA is AAA some sample text. AAA Select this text.' 
    newarr=txt_ins.split(ins)
    getNewInsertIndex(arr,newarr)
    arr=newarr;//txt_ins ='AAA This AAA is AAA some sample text. AAA Select this AAA text.' 
    newarr=txt_ins.split(ins)
    getNewInsertIndex(arr,newarr)
    arr=newarr;//txt_ins ='AAA This AAA is AAA some sample text. AAA Select this AAA text AAA .' 
    newarr=txt_ins.split(ins)
    getNewInsertIndex(arr,newarr)
    arr=newarr;//
      

  4.   

    input 和 textarea可以计算, iframe类型的没弄过,iframe通过textRange就可以很好控制内容了.
      

  5.   


    是想找到最新一次插入的内容的位置!!!是存在没有空格无法分割的问题!!!我尝试过用indexOf先把已有的标志位置存入一个数组;然后再把插入后的新标志位置存入另一个数组,然后比较两个数组.但是发现最终没法比较!!! 谢谢!!!