How can I build a dynamic XPath in JavaScript for Puppeteer?

I’m trying to generate an XPath dynamically for Puppeteer automation. The challenge is that while the beginning and ending of the XPath remain constant, there’s a segment in the middle that changes each time. For example, consider the two similar selectors shown below where only the value inside the curly braces differs:

// Example of a dynamic XPath generation
const randomSegment = 'XYZ987LMN123';
const identifier = 'tableField_' + randomSegment + '_item';
const dynamicSelector = `//*[@id="${identifier}"]`;
console.log(dynamicSelector);

In this scenario, the variable part (inside the curly brackets) is dynamically created, whereas the rest of the XPath is fixed. I need a strategy to reliably generate such selectors in my automation scripts.

hey, try to use template strngs to blend fixed parts and dynamic ones. it worked well in my puppeteer setup and made xpath gen super simple. give it a go, might just do the trick.