js 在字符串中快速查找字符串并指出对应的起始位置和结束位置

let a = 'dafdsafasdfadgdafasfsagadfasfsafsadfsda';
let str = 'da';
let b = a.indexOf(str);
let i = 0;
let locationList = [];
let locationObj = {};

while(a.indexOf(str,i) !== -1){
locationObj = {};
locationObj.startNum = a.indexOf(str,i);
locationObj.endNum = a.indexOf(str,i) + str.length - 1
locationList.push(locationObj);
console.log("开始",i);
console.log("起始位置",a.indexOf(str,i));
console.log("结束位置",a.indexOf(str,i) + str.length - 1);
console.log("三种情况:1、选择位置在首位,2、选择位置在中间,3、选择位置在末尾");
  i = a.indexOf(str,i) + str.length;
}
let d = a.split(str);
for(let i = d.length - 1;i >=0 ; i--){
    if(i !== 0){
      d.splice(i , 0 ,str);
    }
}
if(d[0] === '') d.splice(0,1);
if(d[d.length - 1] === '') d.splice(d.length - 1,1);
console.log("c===================>", d);

let oneList = [];
let oneObj = {
      
    };
for(let i = 0;i<d.length;i++){
    oneObj = {  }
    if(d[i] === str){
        oneObj.text = d[i];
        oneObj.isSelect = true;
        oneObj.isActive = false;
        if(i !== 0) {
            oneObj.startNum = locationList[oneList[i - 1].index].startNum
            oneObj.endNum = locationList[oneList[i - 1].index].endNum
            oneObj.index = oneList[i - 1].index + 1;
        }
        else {
            oneObj.startNum = locationList[0].startNum
            oneObj.endNum = locationList[0].endNum
            oneObj.index = 1
        }
    }else{
        oneObj.text = d[i];
        oneObj.isSelect = false;
        oneObj.isActive = false;
         if(i !== 0) oneObj.index = oneList[i - 1].index;
         else oneObj.index = 0
    }
oneList.push(oneObj);
}
console.log("oneList=================>", oneList);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值