您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

js:使用diff.js实现文本内容差异比较

时间:05-24来源:作者:点击数:

实现效果

在这里插入图片描述

简介

A javascript text differencing implementation.

译文:javascript文本差异实现。

相关文档

安装

npm

npm install diff --save

CDN:

https://unpkg.com/diff@5.1.0/dist/diff.js

示例

1、json比较diffJson
// CommonJS
// const Diff = require('diff')

// EMS
import * as Diff from 'diff'

const one = {
  id: 1,
  name: 'Tom',
  age: 18,
}

const other = {
  id: 2,
  name: 'Jack',
  age: 18,
}

const diff = Diff.diffJson(one, other)

console.log(diff);


输出

[
  { count: 2, value: '{\n  "age": 18,\n' },
  {
    count: 2,
    added: undefined,
    removed: true,
    value: '  "id": 1,\n  "name": "Tom"\n'
  },
  {
    count: 2,
    added: true,
    removed: undefined,
    value: '  "id": 2,\n  "name": "Jack"\n'
  },
  { count: 1, value: '}' }
]
2、按行比较diffLines
// const Diff = require('diff')
import * as Diff from 'diff'

const one = {
  id: 1,
  name: 'Tom',
  age: 18,
}

const other = {
  id: 2,
  name: 'Jack',
  age: 18,
}

const diff = Diff.diffLines(
  JSON.stringify(one, null, 2),
  JSON.stringify(other, null, 2)
)

console.log(diff)

输出

[
  { count: 1, value: '{\n' },
  {
    count: 2,
    added: undefined,
    removed: true,
    value: '  "id": 1,\n  "name": "Tom",\n'
  },
  {
    count: 2,
    added: true,
    removed: undefined,
    value: '  "id": 2,\n  "name": "Jack",\n'
  },
  { count: 2, value: '  "age": 18\n}' }
]
3、比较数组diffArrays
// const Diff = require('diff')
import * as Diff from 'diff'

const one = {
  id: 1,
  name: 'Tom',
  age: 18,
}

const other = {
  id: 2,
  name: 'Jack',
  age: 18,
}

const diff = Diff.diffArrays(
  JSON.stringify(one, null, 2).split('\n'),
  JSON.stringify(other, null, 2).split('\n'),
)

console.log(diff);


// 组装结果
let list = diff.map((part) => {
  if (part.added) {
    return part.value.map(x=>'+' + x).join('\n')
  } else if (part.removed) {
    return part.value.map(x=>'-' + x).join('\n')
  } else {
    return part.value.join('\n')
  }
})

console.log(list.join('\n'))

输出

[
  { count: 1, value: [ '{' ] },
  {
    count: 2,
    added: undefined,
    removed: true,
    value: [ '  "id": 1,', '  "name": "Tom",' ]
  },
  {
    count: 2,
    added: true,
    removed: undefined,
    value: [ '  "id": 2,', '  "name": "Jack",' ]
  },
  { count: 2, value: [ '  "age": 18', '}' ] }
]

组合后输出

{
-  "id": 1,
-  "name": "Tom",
+  "id": 2,
+  "name": "Jack",
  "age": 18
}

总结

通过以上示例可以发现:

  1. json比较的缺点,行的先后顺序 改变了
  2. 按行比较的缺点,有很多的 回车符 \n 不好按行处理
  3. 比较数组较为理想,可以继保留了输入顺序,同时也能够按行处理比较结果
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门