Search code examples
regextypescriptplaywright

Using RegExp as parameter for a locator


I have this function that clicks on a locator and i want to use the locator as a parameter of type string or RegExp

export async function clickRegexLocator(page: Page, locator:string|RegExp) {
    await page.locator(locator).click();
}

The locator looks something like this, where the number 4 always changes to something else and i want to use regex instead of number 4

'#react-select-4-option-0'

My problem is that the function as it is written will display an error saying:

Argument of type 'string | RegExp' is not assignable to parameter of type 'string'.
  Type 'RegExp' is not assignable to type 'string'

What solution is there for me to use regex in this case, in order to go from this

clickRegexLocator(page, '#react-select-4-option-0');

to this ?

clickRegexLocator(page, /#react-select-/\d+-option-0/);

Solution

  • Regex on Ids is not supported yet, you can upvote this feature request.
    You could use a prefix CSS attribute matcher, like locator("[id^=react-select-]") but I would definitely try to find a better way to find that element.