Skip to content
Target QATargetQA
Playwright · TypeScriptLocators & SelectorsBeginner4 min read

Playwright getByText() vs getByRole(): Exact Match, Strict Mode & RegEx Guide

Stop writing fragile XPath just to match visible text. Learn how page.getByText() matches substrings by default, how { exact: true } prevents Strict Mode errors, and when to switch to getByRole().

By TargetQA Engineering Team•Updated 2026-11-20
Interactive Cloud Sandbox

Test this solution live in real cloud browsers

Preload the working test script directly into TargetQA's Playwright compiler. Zero local dependencies or browser drivers needed.

Test Live in Compiler
The Problem & Error Symptoms

Understanding the Breakdown

Teams migrating from Selenium often reach for brittle XPath expressions like `//div[contains(text(),'Welcome')]` or get tripped up by Playwright's Strict Mode violation when `page.getByText('Sign in')` matches both a heading and a button.

Under the Hood

Why Traditional Selectors Fail

By default, `page.getByText()` performs a case-insensitive substring match and normalizes whitespace. If two visible elements contain the substring, Playwright intentionally throws a Strict Mode error instead of clicking the wrong element.

Field-Tested Patterns

Production-Grade Solutions

Choose the strategy that matches your test architecture. Pattern #1 is recommended for most production test suites.

1. Pass { exact: true } to Fix Strict Mode Collisions

Recommended

Lock onto the full trimmed text string (case-sensitive) so partial substring matches are ignored.

1. Pass { exact: true } to Fix Strict Mode Collisions (typescript)
// Matches ONLY an element whose full text is "Sign in"
await expect(page.getByText('Sign in', { exact: true })).toBeVisible();
How it works: Setting `{ exact: true }` turns off substring matching and enforces exact case matching, immediately resolving Strict Mode errors when another element says 'Sign in to continue'.

2. Use a Regular Expression for Dynamic Text

Match dynamic IDs, timestamps, or totals cleanly without hardcoding volatile values.

2. Use a Regular Expression for Dynamic Text (typescript)
// Matches "Order #48291 placed" regardless of order number
await expect(page.getByText(/Order #\d+ placed/i)).toBeVisible();
How it works: Regular expressions keep assertions resilient against dynamic data while still verifying the exact expected format.

3. Prefer getByRole() for Interactive Buttons & Links

Use getByText() for non-interactive copy (headings, alerts, status banners) and getByRole() for clickable controls.

3. Prefer getByRole() for Interactive Buttons & Links (typescript)
// Better for buttons, links, checkboxes, and form controls:
await page.getByRole('button', { name: 'Sign in', exact: true }).click();
await expect(page.getByText(/Welcome back/i)).toBeVisible();
How it works: getByRole() verifies both the visible accessible name and the interactive ARIA semantics, catching accessibility regressions automatically.
Full Executable Cloud Test
Open in compiler

Complete Working Test Script

You can copy this exact test into your repository or run it immediately in our cloud sandbox against live demo targets.

test-recipe.spec.ts
import { test, expect } from '@playwright/test';

test('demonstrate getByText exact, regex, and getByRole', async ({ page }) => {
  await page.setContent(`
    <main>
      <h1>Sign in to TargetQA</h1>
      <button type="button">Sign in</button>
      <p role="status">Order #84219 placed successfully</p>
    </main>
  `);

  // Exact match avoids Strict Mode collision with the <h1>
  await expect(page.getByText('Sign in', { exact: true })).toBeVisible();

  // Prefer getByRole for clickable buttons
  await page.getByRole('button', { name: 'Sign in', exact: true }).click();

  // RegEx matches dynamic order numbers cleanly
  await expect(page.getByText(/Order #\d+ placed/i)).toBeVisible();
});
Target framework: Playwright · Language: TypeScript
Preload & Run in Compiler
Production Checklist

Best Practices & Golden Rules

  • Use `getByText()` for non-interactive text like headings, banners, toast messages, and labels.
  • Use `getByRole()` for interactive buttons, links, tabs, checkboxes, and comboboxes.
  • Add `{ exact: true }` whenever a short word like 'Save' or 'Sign in' appears inside longer text.
  • Pass a RegEx (`/Order #\d+/i`) instead of string concatenation for dynamic numbers.
Avoid Test Flakiness

Common Pitfalls to Avoid

  • Using `.first()` to silence a Strict Mode error instead of narrowing with `{ exact: true }` or `getByRole()`.
  • Using `getByText()` on `<input>` values — inputs do not have inner text; use `getByLabel()` or `toHaveValue()`.

Frequently Asked Questions

Is Playwright getByText() case-sensitive by default?

No. By default `page.getByText('welcome')` is case-insensitive and matches substrings. Passing `{ exact: true }` switches it to full-string, case-sensitive matching.

When should I use getByRole() instead of getByText()?

Use `getByRole()` for interactive controls (buttons, links, inputs, tabs) and `getByText()` for static display text like status banners, descriptions, and non-interactive headings.

How do I fix a Playwright Strict Mode violation with getByText()?

Narrow the locator by passing `{ exact: true }`, switching to `getByRole('button', { name: ... })`, or scoping inside a parent container like `page.locator('form').getByText(...)`.

Hands-On Practice

Practice This Skill in TargetQA Challenges

Explore More Automation Guides