代码之家  ›  专栏  ›  技术社区  ›  umair.ashfr

元素在错误索引处被替换

  •  0
  • umair.ashfr  · 技术社区  · 6 年前

    我有一个whereclause,其中“double aesteric”表示字符串将被替换为代码中secondclause的一部分的位置。我要whereclause变成'(警察!=“kong”)和(king=”king“)和(king=”long“)”。

    我从这个论坛得到了一些帮助,偶然发现了位置功能。不过,在运行代码之后,我得到的是最后一个字符串

    ((警察!=“kong”)*)和(**kon=“link”(king=“king”)

    我该怎么做才对?搞不清这里出了什么问题。

    var whereClause = '(**kon = "link"**) AND (**kon = "link"**) AND (king = "long")';
    var secondClause = '(cop != "kong") AND (king = "king")';
    secondClause = secondClause.split('AND');
    var arr = locations('**', whereClause); //[1, 15, 24, 38]
    
    var whereClause_broken = whereClause.split('');
    var secondIndex = 0;
    for (let index = 0; index <= (arr.length / 2); index += 2) {
      var removed = whereClause_broken.splice(arr[index], arr[index + 1], secondClause[secondIndex]); // arr is modified
      secondIndex++;
    }
    
    whereClause_broken = whereClause_broken.join('');
    
    function locations(substring, string) {
      var a = [],
        i = -1;
      while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i);
      return a;
    }
    1 回复  |  直到 6 年前
        1
  •  0
  •   umair.ashfr    6 年前

    问题是,当我调用locations函数时,它根据字符串在操作之前的状态给出了位置。在for循环中,字符串被操纵,因此原始位置不再有效。必须在循环的每次迭代中调用locations函数以获取最新位置。那解决了我的问题。

    var whereClause = '(**kon = "link"**) AND (**kon = "link"**) AND (king = "long")';
    var secondClause = '(cop != "kong") AND (king = "king")';
    secondClause = secondClause.split(') AND (');
     var counter = locations('**',whereClause);
     var secondIndex = 0;
    
    var new_whereClause = whereClause;
    var secondIndex = 0;
    for (let index = 0; index <= (arr.length / 2); index += 2) {
      var arr = locations('**',new_whereClause);
     //console.log('arr :',arr,secondClause);
    var chucnkStr = new_whereClause.substring(arr[0],arr[1]+2); // adding 2 because substring returns location of second instance one less than actual.
    new_whereClause = new_whereClause.replace(chucnkStr,secondClause[secondIndex].replace(/[()]/g, ''));
     secondIndex ++;
    }