Reputation:
I'm using JavaScript and i have a question about regex. I haven't found exactly what i'm asking so here it goes.
I have a super long regex and i would like to split it into a bunch of more smaller strings to make clear what the regex is validating.
I know that it is possible to split the long regex into smaller ones by doing something like (and this way actually works)
const patternOne = /(\w+:{0,1}\w*@)?/;
const patternTwo = /([a-zA-Z0-9.-]+)/;
const pattern = new RegExp(`^${patternOne.source}${patternTwo.source}$`, 'i');
But i would like to omit the .source
and do something more simpler like
const patternOne = '(\w+:{0,1}\w*@)?';
const patternTwo = '([a-zA-Z0-9.-]+)';
const pattern = new RegExp(`/^${patternOne}${patternTwo}$/`, 'i');
Just using the strings
But when i do for example pattern.test(myString)
i get an error that the regex is invalid.
Maybe i forgot to escape one of my characters? Or is not possible to use just the strings?
Upvotes: 4
Views: 17492
Reputation: 1375
The closest solution to you code is:
const patternOne = String.raw`(\w+:{0,1}\w*@)?`;
const patternTwo = String.raw`([a-zA-Z0-9.-]+)`;
const pattern = new RegExp(`^${patternOne}${patternTwo}$`, 'i');
Upvotes: 3
Reputation: 12478
You need to double escape instead of single escape that is you have to use 2 slashes.
Also you don't have to add /
at the start and end in RegExp
function.
const pattern = new RegExp(`/^${patternOne}${patternTwo}$/`, 'i');
^^ ^^ -> remove those
It will be added automatically
const patternOne = '(\\w+:{0,1}\\w*@)?';
const patternTwo = '([a-zA-Z0-9.-]+)';
const pattern = new RegExp("^" + patternOne + patternTwo + "$", 'i');
console.log(pattern);
Upvotes: 8