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

It's the first time I come across is. I have a div with content but I only need a piece of the text for an assertion and this topic hasn't been covered anywhere
<div class="card-title">Name: New Restaurant</di>
We want to get the restaurant name only in this card using playwright.
Answer
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]
.
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles