一、需求:旧字符串 str1 ,改成新字符串 str2 ,两个字符串不同的地方高亮显示

二、思路:使用 diff-match-patch 进行实现

三、具体步骤:

1、安装

npm install diff-match-patch

2、具体文件进行使用

<template>
  <div id="app">
    <div>
      旧文本:<div>dog1s bark</div> 
      新文本:<div>cat12s bark</div>
    </div>
  </div>
</template>



<script>
  import DiffMatchPatch from 'diff-match-patch';
  
  export default {
    mounted(){
      const dmp = new DiffMatchPatch();
      const diff = dmp.diff_main('dog1s bark', 'cat12s bark')
      var div = document.createElement('div')
      
      diff.forEach(function (item) {
        var span = document.createElement('span')
        span.innerText = item[1]
        
        
         // 删除
        if(item[0] === -1){
          span.style.textDecoration = 'line-through'
          span.style.background = '#ffe6e6'
        }
        
        
        // 插入
        if(item[0] === 1){ 
          span.style.textDecoration = 'underline'
          span.style.background = '#e6ffe6'
        }
        
        
        div.appendChild(span)
      })
      
      
      document.body.appendChild(div)
    }
  }
</script>

3、最终效果如下:

在这里插入图片描述

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐