Front-end new and old string difference comparison function --diff-match-patch

1. Requirements: Change the old string str1 to the new string str2, and highlight the differences between the two strings.

2. Idea: Use diff-match-patch to implement

3. Specific steps:

1. Installation

npm install diff-match-patch

2. Use specific files

<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. The final effect is as follows:

Insert image description here

Guess you like

Origin blog.csdn.net/qq_37600506/article/details/126720614