计算字符串差异作为范围

时间:2014-11-20 08:01:45

标签: javascript

我正在尝试找出用户在字符串中更改了哪些字符。我幸运的是可以假设只有一个,随后的变化块。

我甚至未能找到更改区域的开始位置:

var originalVal, val; //strings
//The ranges
var original = [0,0];
var new_rang = [0,0];
//Old length, new length
var ol = originalVal.length;
var nl = val.length;
//Find where the change begins (that should be the same for both arrays)

for(var i=0; ; i++) {
  //If end of string was reached or the strings are different
  if((i>=ol||i>=nl) || originalVal[i]!=val[i]) {
    original[0] = new_rang[0] = i;
    //Set these to i too, assuming there was no change
    original[1] = new_rang[1] = i;
    break;
  }
}  

如果有一行相同的字符并且用户在中间删除了一行,则完全中断:

  

mmmmx
  米<德尔>米 MMX
  MMM的 X

脚本会说更改发生在4,x移动了。但实际上,似乎甚至无法说哪个 m已被删除。

然而,我可以告诉光标位置在开头的位置和最后的位置。这样看起来更有希望,但我仍然不知道该怎么做:

  

毫米| MMX
  米<德尔>米 | MMX
  米| MMX

这一次,我可以看到删除了哪个m。但我仍然不知道如何向计算机解释它。

1 个答案:

答案 0 :(得分:1)

以下是我认为您可能正在寻找的内容。请澄清你的问题。

&#13;
&#13;
var Console = function() {
  this.log = function(msg) {
    debug(msg)
  };
};
var console = new Console();

function diffLengths(longer, shorter) {
  var indexes = [];
  var isTheSame = true;
  for (var i = 0; i < shorter.length; i++) {
    if (shorter[i] != longer[i]) {
      isTheSame = false;
      indexes.push(i);
    }
  };
  if (isTheSame) {
    // The shorter string is exactly the same as the longer string
    // except for the extra characters in the longer string
    indexes.push(shorter.length);
  }
  return indexes;
}

function getDiffRange(first_string, second_string) {
  var indexes = [];
  if (first_string.length > second_string.length) {
    return diffLengths(first_string, second_string);
  } else if (first_string.length < second_string.length) {
    return diffLengths(second_string, first_string);
  } else {
    for (var i = 0; i < first_string.length; i++) {
      if (second_string[i] != first_string[i]) {
        indexes.push(i);
      }
    };
  }
  return indexes;
}

var range = getDiffRange('mmmmx', 'mmmx');
document.getElementById('result-1').innerHTML = range[0] + " - " + range[range.length - 1];

var range = getDiffRange('mmmmx', 'mmmxc');
document.getElementById('result-2').innerHTML = range[0] + " - " + range[range.length - 1];

var range = getDiffRange('mm', 'mmx');
document.getElementById('result-3').innerHTML = range[0] + " - " + range[range.length - 1];
&#13;
table, th, td {
	border-collapse: collapse;
	border: 1px solid #ddd;
	text-align: left;
	padding: 7px;
}
&#13;
<html>

<body>
  <table>
    <tr>
      <th>input</th>
      <th>result</th>
    </tr>
    <tr>
      <td>'mmmmx', 'mmmx':</td>
      <td id='result-1'></td>
    </tr>
    <tr>
      <td>'mmmmx','mmmxc':</td>
      <td id='result-2'></td>
    </tr>
    <tr>
      <td>'mm','mmx':</td>
      <td id='result-3'></td>
    </tr>
  </table>
</body>

</html>
&#13;
&#13;
&#13;