Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate strings for building a regex?

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?


1 Answers

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);
like image 166
Sagar V Avatar answered Nov 04 '25 17:11

Sagar V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!