[javascript]글 문자열 비교 라이브러리 diff_match_patch.js

게시판에 쓴 글을 기존내용과 비교해서 보여달라는 지령이 떨어졌다.
글 내용은 이미 로그 테이블에 저장이 되어 있었는데 어떤 식으로 보여줄지 고민이 되었다.
구글 검색을 열심히 하다보니 diff_match_patch라는 라이브러리를 발견했다.
 

diff_match_patch

diff match patch는  두 개의 파일이나 두 개의 문자열의 차이점을 보여주는  라이브러리이다.
 
https://github.com/google/diff-match-patch

 

GitHub - google/diff-match-patch: Diff Match Patch is a high-performance library in multiple languages that manipulates plain te

Diff Match Patch is a high-performance library in multiple languages that manipulates plain text. - GitHub - google/diff-match-patch: Diff Match Patch is a high-performance library in multiple lang...

github.com

이 라이브러리로 가능한 기능은 총 3가지가 있다.
 
1.Diff
일반 텍스트의 두 블록을 비교해 효율적으로 반환한다.
 
2.Match
검색 문자열이 주어지면 일반 텍스트 블록에서 가장 일치하는 항목을 찾는다.
 
3.Patch
일반텍스트에 패치목록을 적용한다.

 

실전예제

<div class="jarviswidget" id="wid-id-0" role="widget" >
	<div style="width: 100%;">
		<div id="scrollDiv" style="width: 50%;  float: left; border: 1px solid black;">
			<div id="layerbox" class="layerpop" style="overflow: scroll;max-height:700px;">
			기존내용</div>
		</div>
		<div id="scrollDiv2" style="margin-left: 50%; border: 1px solid black;">
			<div id="layerbox2" class="layerpop" style="overflow: scroll;max-height:700px;">
			현재내용</div> 
		</div>
	</div>
</div>

이 중에서 써볼껀 글을 비교하는 diff 기능.
일단 비교할 문자열을 보여줄 div를 만들었다.
왼쪽 div에는 기존 내용을, 오른쪽 div에는 현재 내용을 넣어줄 것이다.
 

var dmp = new diff_match_patch();
function launch() {
      var text1 = $('#layerbox').html();
      var text2 =  $('#layerbox2').html();
      text1 = $('#layerbox').html().replaceAll('&nbsp;', ' ').replace(/(<br>|<br\/>|<br \/>)/g, '');
      text2 =  $('#layerbox2').html().replaceAll('&nbsp;', ' ').replace(/(<br>|<br\/>|<br \/>)/g, '');

      var d = dmp.diff_main(text1, text2);
      var ds = dmp.diff_prettyHtml(d);
      $('#layerbox2').html(ds.replace(/&para;/g, ''));
}
launch();

lanuch() 스크립트를 실행했다.
div 안 내용을 읽어 각각 text1, text2 변수에 담은 후 공백과 br태그도 제거한다.
diff_main(text1, text2)을 이용해 내용 2개를 비교한다.
 
비교 후 반환받은 내용은 diff_prettyHtml(diffs)를 통해  예쁜 HTML 시퀀스로 반환한다.
마지막으로 결과물을 오른쪽 div에 다시 넣어준다.
 

스크립트를 실행해 보면 삭제된 내역은 빨간색으로 표기(<del>)되고 추가된 내역은 초록색으로 표기(<ins>) 된다.
이렇게 원본을 왼쪽에 보여주고 오른쪽에 원본과 바뀐 내역을 같이 보여주니 어떻게 바뀌었는지 한눈에 알 수 있다.

 

ins태그와 del 태그를 변환하거나 css를 수정할 때에는 diff_match_patch.js 안에 있는 diff_prettyHtml 메서드를 수정하면 쉽게 수정이 가능하다.