元素在错误的索引处被替换

时间:2018-07-01 16:21:46

标签: javascript string

我有一个whereClause,其中“ double aesteric”表示将字符串替换为代码中所示的secondClause的一部分的位置。我希望whereClause成为'(cop!=“ kong”)AND(king =“ king”)AND(king =“ long”)'”。

我从这个论坛上获得了一些帮助,偶然发现了位置功能。但是,在运行代码后,我将其作为最终字符串

  

(((cop!=“ kong”)*)AND(** 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 个答案:

答案 0 :(得分:0)

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

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 ++;
}