differences
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://unpkg.com/diff@4.0.2/dist/diff.min.js"></script>
<div><input id="input-1" value="The quick brown fox" /></div>
<div><input id="input-2" value="The quick brown fox jumped over the fence" /></div>
<button id="show-diff">Show diff</button>
<button id="hide-diff">Hide diff</button>
<div id="output"></div>
CSS
[data-diff="added"] {
color: green;
}
[data-diff="removed"] {
color: red;
}
JavaScript
document.getElementById('show-diff').addEventListener('click', () => {
const diff = Diff.diffChars(document.getElementById('input-1').value, document.getElementById('input-2').value);
const output = diff.reduce((result, change) => {
if (change.added) return result + '<span data-diff="added">' + change.value + '</span>';
if (change.removed) return result + '<span data-diff="removed">' + change.value + '</span>'
return result + change.value;
}, '');
document.getElementById('output').innerHTML = output;
console.log(output);
});
document.getElementById('hide-diff').addEventListener('click', () => {
const output = document.getElementById('output').innerHTML;
document.getElementById('output').innerHTML = output.replace(/<span data-diff=["'](?:added|removed)["']>(.+)<\/span>/gi, '$1');
});