JavaScript 字符串差异对比

2021/10/22 17:39:33

本文主要是介绍JavaScript 字符串差异对比,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

getHighLightDifferent(a, b) {
        var temp = this.getDiffArray(a, b);
        var a1 = this.getHighLight(a, temp[0]);
        var a2 = this.getHighLight(b, temp[1]);
        return new Array(a1, a2);
      },
      getHighLight(source, temp) {
        var result = [];
        var sourceChars = source.split("");
        var tempChars = temp.split("");
        var flag = false;
        for (var i = 0; i < sourceChars.length; i++) {
          if (tempChars[i] != ' ') {
            if (i == 0) {
              result.push("<span style='color:red'>");
              result.push(sourceChars[i]);
            } else if (flag) {
              result.push(sourceChars[i]);
            } else {
              result.push("<span style='color:red'>");
              result.push(sourceChars[i]);
            }
            flag = true;
            if (i == sourceChars.length - 1) {
              result.push("</span>");
            }
          } else if (flag == true) {
            result.push("</span>");
            result.push(sourceChars[i]);
            flag = false;
          } else {
            result.push(sourceChars[i]);
          }
        }
        return result.join('');
      },
      getDiffArray(a, b) {
        var result = new Array();
        //选取长度较小的字符串用来穷举子串
        if (a.length < b.length) {
          var start = 0;
          var end = a.length;
          result = this.getDiff(a, b, start, end);
        } else {
          var start = 0;
          var end = b.length;
          result = this.getDiff(b, a, 0, b.length);
          result = new Array(result[1], result[0]);
        }
        return result;
      },
      //将a的指定部分与b进行比较生成比对结果
      getDiff(a, b, start, end) {
        var result = new Array(a, b);
        var len = result[0].length;
        while (len > 0) {
          for (var i = start; i < end - len + 1; i++) {
            var sub = result[0].substring(i, i + len);
            var idx = -1;
            if ((idx = result[1].indexOf(sub)) != -1) {
              result[0] = this.setEmpty(result[0], i, i + len);
              result[1] = this.setEmpty(result[1], idx, idx + len);
              if (i > 0) {
                //递归获取空白区域左边差异
                result = this.getDiff(result[0], result[1], start, i);
              }
              if (i + len < end) {
                //递归获取空白区域右边差异
                result = this.getDiff(result[0], result[1], i + len, end);
              }
              len = 0; //退出while循环
              break;
            }
          }
          len = parseInt(len / 2);
        }
        return result;
      },
      //将字符串s指定的区域设置成空格
      setEmpty(s, start, end) {
        var array = s.split("");
        for (var i = start; i < end; i++) {
          array[i] = ' ';
        }
        return array.join("");
      },


这篇关于JavaScript 字符串差异对比的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程