效果:
案例:
strA = '点击图标下载 App'
strB = '点击App图标下载应用'
结果:
/*
strA变成strB
0:不变的字段;
1:新增的字段
-1:删除的字段
*/
0: [0, "点击"]
1: [1, "App"]
2: [0, "图标下载"]
3: [-1, " App"]
4: [1, "应用"]
主要实现:
使用第三方库‘diff_match_patch’, 有各种语言的实现版本,
地址:
https://github.com/google/diff-match-patch
api:
https://github.com/google/diff-match-patch/wiki/API
JS版本的详细实现:
安装:
npm install diff_match_patch
使用:
import DiffMatchPatch from 'diff-match-patch';
let str1 = '点击图标下载 App';
let str2 = '点击App图标下载应用';
let dmp = new DiffMatchPatch();
let diffs = dmp.diff_main(str1, str2);
console.log(diffs) //[0: [0, "点击"]
//1: [1, "App"]
//2: [0, "图标下载"]
//3: [-1, " App"]
//4: [1, "应用"]]