-2

Ok, let's say I have a list of prefixes that I'd want to use in a RegExp, that would look something like this:

const prefixes = ["*","|","^"];
const prefixDetector = new RegExp(`^${prefixes.join('|')}`, 'gmi');

That's great and all, but the only issue is that my RegExp comes out like this:

const regex = /^*|||^/gmi
//What Went Wrong: "|||" will search for blank characters, A.K.A "".

It should come out like this.

const regex = /^\*|\||\^/gmi
//Expected

I could use code that looks like this:

...
const prefixDetector = new RegExp(`^\\${prefixes.join('|\\')}`, 'gmi');

Assuming it'll come out as the code above, but when I add prefixes like this:

const prefixes = ['*','|','^','b','s'];

I would get something like this:

const regex = /^\*|\||\^|\b|\s/gmi
//What Went Wrong: It is correct, but "\b" and "\s" are Regex tokens in Javascript.

Remember, \b and \s is for word boundaries and whitespace characters.

What I'm trying to get here is to match prefixes, and the prefixes can be longer than 1 character and be customizable, so something like /[%%]/gmi wouldn't cut it, because that only handles 1 character.

So it would be like:

const prefixes = ['%%', 'b', 'percentage', 'percent'];
const RegExp = new RegExp('...?', 'gmi');
//test RegExp on something like "%%afterprefix" or "percentthing";
SomePerson
  • 1,171
  • 4
  • 16
  • 45

1 Answers1

-2

To prevent Regex from interpreting those characters with special meaning you have to escape it in your array.

E.g ["\\s", "\\b", "\\|", "\\^"]

SomePerson
  • 1,171
  • 4
  • 16
  • 45
Fritzdultimate
  • 372
  • 2
  • 11