Reputation: 1146
For example, if I want to match ips, can I break it up like so:
const octet = /\d{1,3}/;
const ip = /{octet}\.{octet}\.{octet}\.{octet}/;
Upvotes: 3
Views: 287
Reputation: 2119
With an already declared regular expression literal, you can use its source
property to get the version without the enclosing tags. Using template literals inside a new RegExp
constructor, create your new expression.
const octet = /\d{1,3}/;
const octetSource = octet.source;
const ip = new RegExp(`^${octetSource}\\.${octetSource}\\.${octetSource}\\.${octetSource}$`);
Upvotes: 6
Reputation: 24191
You could mix using new RegExp()
and template literals to do it similar.
Below is an example.
const octet = /\d{1,3}/;
const octetS = octet.source;
const ip = new RegExp(
`^${octetS}\\.${octetS}\\.${octetS}\\.${octetS}$`);
const ips = [
'127.0.0.1',
'10.0.2',
'12.10.2.5',
'12'];
for (const checkip of ips)
console.log(`IP: ${checkip} = ${ip.test(checkip)}`);
Upvotes: 8