TIL: String.raw
- til
I've always used \\ to keep backslashes literal in strings. That works great until you're writing dynamic regex patterns and all those backslashes become hard to read.
Today, while reviewing a PR, I learned about String.raw. It preserves backslashes while still letting me interpolate variables:
const prefix = "invoice";
const doubled = new RegExp(`^${prefix}-\\d+$`);
const raw = new RegExp(String.raw`^${prefix}-\d+$`);
console.log(raw); // /^invoice-\d+$/
console.log(doubled.source === raw.source); // true
console.log(raw.test("invoice-123")); // true← All writing
2 likes