日期:2014-05-16  浏览次数:20537 次

js or jquery 字符串 插入 字符 的 位置 计算
  如何获取插入字符的位置?比如:
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.'  ;
 



------解决方案--------------------
楼主是想找到最新一次插入的内容的位置是吧?

大概写了个。。有个小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;//