我正在遵循 https://github.com/google/diff-match-patch 和
var text = "<div class='hover'>nHello worldn</div>";
var text2 = "<div class='hover'>nHello whirldn</div>";
var dmp = new diff_match_patch();
var result = dmp.diff_main(text, text2, false);
当我查看对象时,结果是:
Array {
0 0,<div class='hover'>
Hello w
1 -1,o
2 1,hi
3 0,rld
</div>
}
文档说它返回一个元组数组。如何获取第一个差异的行号和行号?如果我能够获得第一个更改,那是奖励,但不是必需的。
创建上面的示例后,看起来我可以找到第一个-1
,那就是行?我希望有一种方法可以做这样的事情:
var result = dmp.diff_main(text, text2, false);
Object {
row: 1,
column: 4,
original: "hello world",
changed: "hello whirld"
}
如果我更改第 3 行,结果如下:
var text = "<div class='hover'>nHello worldn</div>";
var text2 = "<div class='hover'>nHello worldn</div2>";
var dmp = new diff_match_patch();
var result = dmp.diff_main(text, text2, false);
结果如下:
Array {
0 0,<div class='hover'>
Hello world
</div
1 1,2
2 0,>
}
所以看起来结果没有行号?
https://github.com/google/diff-match-patch
这种工作:
var text = "<div class='hover'>nHello worldn</div>";
var text2 = "<div class='hover'>nHello worldn</div2>";
var dmp = new diff_match_patch();
var result = dmp.diff_main(text, text2, false);
var LINE_BREAK = "n";
var lines = [];
var row = 1;
var column = 0;
var firstResult = result && result[0] ? result[0] : null;
var operation = firstResult ? firstResult[0] : null;
var data = firstResult ? firstResult[1] : null;
var lastLine = "";
if (data && data.indexOf(LINE_BREAK)!=-1) {
lines = data.split(LINE_BREAK);
lastLine = lines[lines.length-1];
row = lines.length;
column = lastLine.length;
}