Home > Software engineering >  Possible to get 'regex source' from match?
Possible to get 'regex source' from match?

Time:02-13

I can get the source of a regex when it's defined separately. For example:

let r1 = new RegExp("el*");
console.log(r1.source);
// el*

Or:

let r2 = /el*/;
console.log(r2.source);
// el*

Is there a way to extract that if the regex isn't defined separately? For example, something along the lines of:

let m = "Hello".match(/el*/);
console.log(m.source?);

CodePudding user response:

No,

quoting the documents of the match() function

Return value

An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

So the return value is an array (you can test it by Array.isArray(m)// true)

So there is no information with respect of the match cause the return value is a standard Array

  • Related