Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
Possible to get 'regex source' from match?

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?);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

However, the returned array has some extra information about the ocurred match (like groups, index and original input) but none of them include the original regex used to get the match

So there is no way to get that information from the match because its not returned by the matching function

about 4 years ago · Juan Pablo Isaza Report

0

The match result by itself cannot lead to the original regex, simply because different regexes can lead to the same result, even on the same string. Take for example the string "abcd" - all the following regexes: /abcd/, /a..d/ /a.*/ and many more, would match the string exactly the same way.

The only way you could retrive the original regex is if a reference to the regex was literally stored by the match() method inside the returned object. There is no reason to think that's the case, but you can implement your own match function that would do. Something like

function myMatch(str, regex) {
  var match = str.match(regex);
  if (match === null) {
    match = [null];
  }
  match.source = regex;
  return match;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!