3

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}/;
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
Ace
  • 1,028
  • 2
  • 10
  • 22

2 Answers2

8

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)}`);
Keith
  • 22,005
  • 2
  • 27
  • 44
  • Note that this does not make `octet` a regex, though, instead making it what is effectively a magic string. Sven's solution, taking advantage of the JS RegEx `source` property, is probably better here. – Mike 'Pomax' Kamermans May 01 '19 at 15:38
  • @Keith Your original answer was sufficient and how I was going about it already. I was just wondering if I could not involve template literals. – Ace May 01 '19 at 16:39
  • Note that template literals _are strings_, just better (because they're almost always implemented as faster than plain strings, while also avoiding the problems of quote nesting and string concatenation quirks) so wanting to avoid them in favour of plain strings doesn't make a lot of sense. – Mike 'Pomax' Kamermans May 02 '19 at 14:32
  • @Mike'Pomax'Kamermans I wanted to avoid them in favor of escaping the variable using regex syntax, however there just seems to be no syntax for that. – Ace May 08 '19 at 17:34
6

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}$`);
Namaskar
  • 2,114
  • 1
  • 15
  • 29
  • Using the `source` is a good idea, but you will still need to escape the backslash inside you string literal, .. `${octetSource}\\.$` – Keith May 01 '19 at 15:37
  • There is not better / worse answer IMO, your source was a good idea and is why I up-voted your answer, and then blatantly used it myself, more because someone down-voted me, and with `octet` not strictly been a true regEx, might have upset them. – Keith May 01 '19 at 16:00
  • Keith's original answer was actually how I was attempting it already. Seeing as how template literals are ultimately needed, I don't need to define any "true" regex. It is very useful to know about the source property though. – Ace May 01 '19 at 16:34