Text Diff

Compare two texts side by side and highlight line-by-line differences

Try an example

Text A

Text B

Runs locally · Safe to paste secrets
Runs locally · Safe to paste secrets

What is Text Diff?

A text diff (short for "difference") is the result of comparing two blocks of text and identifying which lines were added, removed, or left unchanged. The concept originates from the Unix diff utility, first released in 1974 as part of Version 5 Unix. Today, text diff is the backbone of version control systems like Git, where every commit stores a diff rather than a full copy of each file.

A diff algorithm finds the Longest Common Subsequence (LCS) between two sequences of lines. Lines present in the LCS are marked as unchanged. Lines in the original text but not the LCS are marked as removed. Lines in the modified text but not the LCS are marked as added. The result is a minimal set of changes needed to transform one text into the other.

Diff output comes in several formats. Unified diff (the default for git diff) prefixes removed lines with a minus sign and added lines with a plus sign. Side-by-side diff arranges both texts in parallel columns. This tool uses line-by-line comparison with color-coded output: green for additions, red for removals, and neutral for unchanged lines. Unchanged lines are shown with no prefix by default but can be hidden to focus only on what changed.

Why Use an Online Text Diff Tool?

Comparing text in a terminal requires installing diff utilities and dealing with command-line flags. A browser-based diff tool removes that friction entirely.

Instant comparison
Paste two text blocks and see differences highlighted immediately. No file creation, no commands to remember, no output to parse.
🔒
Privacy-first processing
All comparison happens in your browser using JavaScript. Your text never leaves your device, which matters when diffing configuration files, credentials, or proprietary code.
📋
Copy-ready output
The diff output uses standard + / - prefixes that match unified diff format. You can copy the result directly into commit messages, code review comments, or bug reports.
🌐
No login or install required
Works on any device with a browser. No account creation, no extension, no desktop app. Open the page and start comparing.

Text Diff Use Cases

Frontend Development
Compare minified CSS or HTML output before and after a build step to catch unintended changes in generated markup or styles.
Backend Engineering
Diff API responses across environments (staging vs production) to verify that a deployment did not introduce unexpected data changes.
DevOps & Infrastructure
Compare Kubernetes manifests, Terraform plans, or Nginx configs before applying changes to a live cluster or server.
QA & Testing
Verify that test output matches expected baselines by diffing the actual result against a stored snapshot file.
Data Engineering
Compare CSV headers or SQL schema definitions across database migrations to confirm columns were added or renamed correctly.
Learning & Coursework
Compare your solution to a reference implementation line by line to find where your logic diverges from the expected approach.

Diff Output Formats Compared

Diff tools produce output in several formats. The table below summarizes the most common ones, what generates them, and when each is useful.

FormatTool / SourceDescription
Unified diffdiff -u / git diffPrefixes lines with + / - / space; includes @@ hunk headers
Side-by-sidediff -y / sdiffTwo columns, changed lines aligned horizontally
Context diffdiff -cShows changed lines with surrounding context, marked with ! / + / -
HTML diffPython difflibColor-coded HTML table with inline change highlights
JSON PatchRFC 6902Array of add/remove/replace operations on a JSON document

How Line Diff Works: The LCS Algorithm

Most line-diff tools, including this one, use the Longest Common Subsequence (LCS) algorithm. LCS finds the largest set of lines that appear in both texts in the same relative order, without requiring them to be contiguous. The lines not in the LCS are the actual differences.

The standard LCS algorithm uses dynamic programming and runs in O(m x n) time, where m and n are the line counts of the two texts. For large files, optimized variants like Myers' diff algorithm (used by Git) reduce this to O(n + d^2) where d is the number of differences, making it fast when most lines are shared.

1. Build the DP table
Create an (m+1) x (n+1) matrix. For each pair of lines, store the length of the longest common subsequence seen so far. Equal lines extend the diagonal value by 1.
2. Backtrack
Walk from the bottom-right corner of the matrix back to (0,0). Diagonal moves on equal lines produce "unchanged" entries. Horizontal or vertical moves produce "added" or "removed" entries.
3. Render output
Map each entry to a display line: unchanged lines get no prefix, added lines get +, removed lines get -. Apply color coding for visual clarity.

Code Examples

Implementations of line-by-line text comparison in JavaScript, Python, Go, and the command line. Each example produces unified-style diff output.

JavaScript
// Line-by-line diff using the LCS algorithm
function diffLines(a, b) {
  const linesA = a.split('\n')
  const linesB = b.split('\n')

  // Build LCS table
  const m = linesA.length, n = linesB.length
  const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0))
  for (let i = 1; i <= m; i++)
    for (let j = 1; j <= n; j++)
      dp[i][j] = linesA[i-1] === linesB[j-1]
        ? dp[i-1][j-1] + 1
        : Math.max(dp[i-1][j], dp[i][j-1])

  // Backtrack to produce diff
  const result = []
  let i = m, j = n
  while (i > 0 || j > 0) {
    if (i > 0 && j > 0 && linesA[i-1] === linesB[j-1]) {
      result.unshift({ type: 'equal', text: linesA[i-1] }); i--; j--
    } else if (j > 0 && (i === 0 || dp[i][j-1] >= dp[i-1][j])) {
      result.unshift({ type: 'add', text: linesB[j-1] }); j--
    } else {
      result.unshift({ type: 'remove', text: linesA[i-1] }); i--
    }
  }
  return result
}

const diff = diffLines("alpha\nbeta\ngamma", "alpha\nbeta changed\ngamma\ndelta")
// → [
//   { type: 'equal',  text: 'alpha' },
//   { type: 'remove', text: 'beta' },
//   { type: 'add',    text: 'beta changed' },
//   { type: 'equal',  text: 'gamma' },
//   { type: 'add',    text: 'delta' }
// ]
Python
import difflib

text_a = """alpha
beta
gamma""".splitlines()

text_b = """alpha
beta changed
gamma
delta""".splitlines()

# Unified diff (same format as git diff)
for line in difflib.unified_diff(text_a, text_b, fromfile='a.txt', tofile='b.txt', lineterm=''):
    print(line)
# --- a.txt
# +++ b.txt
# @@ -1,3 +1,4 @@
#  alpha
# -beta
# +beta changed
#  gamma
# +delta

# HTML side-by-side diff
d = difflib.HtmlDiff()
html = d.make_file(text_a, text_b, fromdesc='Original', todesc='Modified')
Go
package main

import (
	"fmt"
	"strings"
)

// Minimal LCS-based line diff
func diffLines(a, b string) {
	la := strings.Split(a, "\n")
	lb := strings.Split(b, "\n")
	m, n := len(la), len(lb)

	dp := make([][]int, m+1)
	for i := range dp {
		dp[i] = make([]int, n+1)
	}
	for i := 1; i <= m; i++ {
		for j := 1; j <= n; j++ {
			if la[i-1] == lb[j-1] {
				dp[i][j] = dp[i-1][j-1] + 1
			} else if dp[i-1][j] >= dp[i][j-1] {
				dp[i][j] = dp[i-1][j]
			} else {
				dp[i][j] = dp[i][j-1]
			}
		}
	}

	var result []string
	i, j := m, n
	for i > 0 || j > 0 {
		if i > 0 && j > 0 && la[i-1] == lb[j-1] {
			result = append([]string{" " + la[i-1]}, result...)
			i--; j--
		} else if j > 0 && (i == 0 || dp[i][j-1] >= dp[i-1][j]) {
			result = append([]string{"+" + lb[j-1]}, result...)
			j--
		} else {
			result = append([]string{"-" + la[i-1]}, result...)
			i--
		}
	}

	for _, line := range result {
		fmt.Println(line)
	}
}

// Output:
//  alpha
// -beta
// +beta changed
//  gamma
// +delta
CLI (diff / git)
# Compare two files with unified diff (3 lines of context)
diff -u original.txt modified.txt

# Git diff between working tree and last commit
git diff HEAD -- file.txt

# Git diff between two branches
git diff main..feature -- src/

# Side-by-side diff in the terminal
diff -y --width=120 original.txt modified.txt

# Color-coded diff (requires colordiff)
diff -u original.txt modified.txt | colordiff

Frequently Asked Questions

What is the difference between a line diff and a character diff?
A line diff compares text line by line: if any character on a line changes, the entire line is marked as removed and the new version is marked as added. A character diff (or word diff) operates at a finer granularity, marking the specific characters or words that changed within a line. Line diff is standard for code review; character diff is more useful for prose editing.
How does git diff work internally?
Git uses Myers' diff algorithm by default, which finds the shortest edit script (the minimum number of insertions and deletions) between two files. Git stores the result in unified diff format with @@ hunk headers that indicate line numbers. When you run git diff, Git compares the working tree against the index (staging area), not the last commit, unless you pass HEAD explicitly.
Can I diff binary files with a text diff tool?
No. Text diff tools split input on newline characters and compare strings. Binary files contain arbitrary byte sequences that produce meaningless line splits. For binary comparison, use a hex diff tool or a file-level checksum comparison (sha256sum on both files).
Is my data sent to a server when using this tool?
No. This tool runs entirely in your browser. The diff computation uses a JavaScript LCS implementation that executes client-side. No network requests are made with your text content. You can verify this by opening your browser's Network tab while using the tool.
What is unified diff format?
Unified diff is the output format used by diff -u and git diff. It shows changed lines with - (removed) and + (added) prefixes, preceded by @@ headers that specify the line number ranges in both files. Context lines (unchanged) have a space prefix. Unified diff is the most common format for patches, pull requests, and code review tools.
How do I compare large files with many differences?
For files with thousands of lines, a browser-based tool works but may slow down because the LCS algorithm scales quadratically. For very large diffs, command-line tools like diff or git diff are faster because they use optimized C implementations and can stream output. You can also filter unchanged lines (toggle off "Show unchanged lines" in this tool) to focus on changes only.
What is a three-way merge diff?
A three-way merge compares two modified versions of a file against their common ancestor (the base). Git uses this during git merge and git rebase. It identifies changes made in each branch relative to the base and combines them. When both branches modify the same line, Git reports a merge conflict. Three-way merge requires three inputs, while a standard diff only needs two.