Home > front end >  get the static part of a RegExp
get the static part of a RegExp

Time:01-20

I want to get the static part of a RegExp string, which 100% guaranteed to not have a regex-specific characters, except the grouping parentheses ().

for instance, this regex /path\/config-(. )\/.js/ has a static part /path/config- until the character '.'

use cases:

I want to search for all matched entries inside a folder that have too many files and subfolders.

so, it is a bit faster to start searching from the basic path /path that doesn't needed to be matched against, instead of starting from the root directory.

CodePudding user response:

Use regex to parse your regex. For the example you showed, you can use:

firstRegexExpr = '/path\/config-(. )\/.js/';
secondRegexExpr = /(.*)\(/;
match = firstRegexExpr.match(secondRegexExpr);

console.log(`Path: ${match[1]}`); // Path: /path/config- 

CodePudding user response:

Based on the "special characters" in this answer, you can use:

const extractPrefix = (re) => {
  const partPattern = /^[^.* ?^${}()|[\]] /g;
  let part = re.source.match(partPattern)[0];
  if (part) {
    part = part.replace(/\\/g, "");
  }
  return part;
};

const re = /path\/config-(. )\/.js/g;
document.getElementById("output").textContent = extractPrefix(re);
<pre id="output"></pre>

  •  Tags:  
  • Related