Skip to content

jsdiff 实现统计修改的字数

引入 jsdiff

shell
npm install diff --save

工具函数封装

ts
import { diffChars } from 'diff';

/**
 * 计算两段文本之间变更的字符数
 * @param {string} oldText 原始文本
 * @param {string} newText 新文本
 * @returns {number} 修改了多少字(字符) = 删除 + 新增
 */
export function countChangedChars(oldText: string, newText: string) {
  const diffs = diffChars(oldText, newText);
  let changed = 0;

  diffs.forEach(part => {
    if (part.added || part.removed) {
      changed += part.value.length;
    }
  });

  return changed;
}

如有转载请标注本站地址