Explain Codes LogoExplain Codes Logo

How do you use a variable in a regular expression?

javascript
regex
dynamic-patterns
input-validation
Nikita BarsukovbyNikita Barsukov·Aug 19, 2024
TLDR

Combine variables and regex in JavaScript by creating a RegExp object.

let term = 'example'; let regex = new RegExp(term, 'i'); // Bingo! You scored /example/i combi

Toss the variable as a string in RegExp with duck-tails or flags ('i' here - because why scream when you can whisper?). This lets you play matching games on the fly.

How to escape and not to be awkward at parties

Reality check: special characters in regex context are misunderstood souls (. ? * + | ( )) - make them feel at home by escaping them:

function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // Because comfort zones are cozy } let term = 'example.'; let safeTerm = escapeRegExp(term); let regex = new RegExp(safeTerm, 'g'); // Escapism champion: /example\./g

Feeling global? Slap in the g flag and replace every instance:

let content = 'An example with another example.'; let newContent = content.replace(regex, 'test'); // No more examples. Only tests here.

Substitution, because who doesn't love a good switcheroo:

let price = 'Prices start at $3.99'; let currency = '\\$'; let regex = new RegExp(currency, 'g'); price = price.replace(regex, '€'); // Initial '$' was so mainstream...

With syntax nuisances, remember: constructor syntax (new RegExp) takes charge when your patterns are dynamic divas.

Why regex when you can just...not

For over-simple replacements, Regex might as well be a hammer for a thumbtack:

let greeting = 'Hello, Jane!'; greeting = greeting.split('Jane').join('John'); // Jane who?

This replaces names without needing a complex formula. Simple wins.

Regex: The Masterclass

Embed your variable within a context in your regex. It's like engraving initials on a ring:

let prefix = 'User'; let regex = new RegExp(`\\b${prefix}\\d{2}\\b`, 'g'); // Bounty hunting 'User' with any two numbers as companions.

Here, template literals and double backslashes are like mints and lip balm on a date – setting up the right context.

Case-insensitive searches need the gentler 'i' flag:

let insensitiveSearch = new RegExp(variable, 'gi');

Examples and pitfalls – the good, the bad, the ugly

Validating inputs with regex

Double-check when validating user input, like an email, with regex. Because regex isn't a swiss army knife:

let emailPattern = /^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,6}$/; let email = userInput; let emailRegex = new RegExp(emailPattern); let isValid = emailRegex.test(email); // Cousin to the immigration officer

Dynamic pattern building

Dynamic patterns are unpredictable like weather: here, RegExp syntax dons the weatherman's hat:

let basePattern = 'file'; let dynamicPart = '2023'; // Because we're so future let fullPattern = `${basePattern}_${dynamicPart}`; let regex = new RegExp(fullPattern);

The escape artist

A literal backslash in your pattern \\ is as elusive and chilling as the 'He who must not be named'. Whip the sorcery out:

let filePath = 'C:\\Documents\\Reports'; let cleanPath = filePath.replace(new RegExp('\\\\', 'g'), '/'); // Your path, your rules