-1

I am refactoring a series of RegExp a/b patterns that are used in two ways.

One uses the ^ as the third character.

/[^a-zA-Z0-9,?@&!#'"~ _;\.\*\/\-\+ ]/

The other doesn't use the ^

/[a-zA-Z0-9,?@&!#'"~ _;\.\*\/\-\+ ]/

Rather than write this pattern in two way is there a way to write it once and add the ^ to a second version?

This throws an error but as an example is there something available like this?

varOne = /[a-zA-Z0-9,?@&!#'"~ _;\.\*\/\-\+ ]/

varTwo = [varOne.slice(0, 1), '^', varOne.slice(1)].join('')

DR01D
  • 1,325
  • 15
  • 32
  • What are you *trying* to do? Do you understand what the `^` means in this context (it’s a special character)? If you want help, please provide an explanation of what you want to do, what you’ve tried, and what’s wrong with your efforts. Please read about [**How to Ask questions here**](http://stackoverflow.com/questions/how-to-ask). – elixenide Jul 12 '18 at 00:21
  • @Ed Cottrell I'm attempting to add a character into a RegExp pattern. Very useful if possible. – DR01D Jul 12 '18 at 00:22
  • Also, that last line is almost certainly not something you want. – elixenide Jul 12 '18 at 00:22
  • Okay, but *what does that mean*? What are you trying to add, where, and for what purpose? Hint: you can’t just insert `^` anywhere you want in a regex. What are you trying? What’s the problem you’re really trying to solve? – elixenide Jul 12 '18 at 00:24

1 Answers1

1

You need to use the RegExp constructor to generate a regex from string:

const regex = caret => `[${caret ? '^' : ''}a-zA-Z0-9,?@&!#'"~ _;\\.\\*\\/\\-\\+ ]`

const regex1 = new RegExp(regex(true));
const regex2 = new RegExp(regex(false));

console.log(regex1.test('%'));
console.log(regex1.test('abc'));

console.log(regex2.test('abc'));
console.log(regex2.test('%'));
Alan Friedman
  • 1,582
  • 9
  • 7
  • I knew the RegExp constructor existed but I never used it before because I couldn't see the practical need for it. Now I understand why we've got that option. – DR01D Jul 12 '18 at 00:41