Playwright locator.textContent() with regex to get a match

Here’s how to use playwrights locator.textContent() with regex to only get what you need.

This would be the conventional idea:

const title = await page.locator('.card-title').textContent() // Name:New Restaurant 
const str = title.slice(5) // New style Restaurant

const str = title.slice(5) gives us what we need but instead, I propose:

const title = await page.locator('.card-title').textContent(/(?<=:).*/) // ['New Restaurant', index: 5, input: 'Name:New Restaurant', groups: undefined]

This regex will get everything behind “:\ so the final useful variable would be title[0].

Read more here: Source link