0

I want to make an input where users can write a custom regex in literal notation. I then want to create a RegExp out of that literal notation string.

Something like this:

const literalNotationStr = `/literal/i`;
const regex = makeRegexFromLiteralNotationString(literalNotationStr)

function makeRegexFromLiteralNotationString(str: string): RegExp {
  // ... magic code ...
}

Is there a function I'm missing here or is this the kind of thing where you have to parse and build yourself?

17
  • 1
    Since it's from an input, do they really need to provide the / delimiters? Other sites that do this put the delimiters outside the input to show that they're not needed. The flags could go in a separate input. Commented Oct 28, 2020 at 1:13
  • ...or the way regex101 does it is pretty nice. Commented Oct 28, 2020 at 1:17
  • 1
    You say literal notation string but what does that mean ? If you have an input box, everything that is typed in that box goes into a variable unchanged. That variable is passed to the RegExp function unchanged. I guess I don't understand. Commented Oct 28, 2020 at 1:17
  • @Maxt8r: They mean the content of the string contains regex literal notation. Commented Oct 28, 2020 at 1:19
  • If on the otherhand, you are trying to parse delimiters for some reason, you make the same mistake as regex101.com does, it's an added user burdon that should not be . Commented Oct 28, 2020 at 1:19

2 Answers 2

0

You'll have to

(1) grab the flags

(2) slice off the slash delimiters from the beginning and end of the pattern

const literalNotationStr = `/literal/i`;
const regex = makeRegexFromLiteralNotationString(literalNotationStr)
console.log(regex.test('LITERAL'));

function makeRegexFromLiteralNotationString(str){
  const [, patternContent, flags] = str.match(/^\/(.+)\/(\w*)$/);
  return new RegExp(patternContent, flags);
}

But you'll have to make sure the input string has its backslashes properly escaped, eg:

const literalNotationStr = String.raw`/foo\w+/i`;

and not

const literalNotationStr = `/foo\w+/i`;
Sign up to request clarification or add additional context in comments.

Comments

-1

The flag has to be provided as the second argument. You can e.g. split the literal to get the Regex body and the flag separately and then use it within the Regex constructor.

const literalNotationStr = '/literal/i';

const createRegex = (str) => {
   const [, literal, flag] = str.split('/');
   return new RegExp(literal, flag);
};

console.log(createRegex(literalNotationStr));

1 Comment

You can't reliably use split for this, since the character you're splitting on can be used within the regex itself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.