Use regular expression with Javascript RegExp constructor

I have a regular expression like this and it works fine using

([a-zA-Z0-9-.~%!$&'()*+,;[email protected]]+(/[a-zA-Z0-9-.~%!$&'()+,;=:@]+)/?|(/[a-zA-Z0-9-.~%!$&'()*+,;=:@]+)+/?)(?[a-zA-Z0-9-.~%!$&'()+,;=:@/?])?(#[a-zA-Z0-9-._~%!$&'()+,;=:@/?])?

I would like to use it with RegExp() like below(I just put the above string inside the raw string), but it does not work. Do I need to do any other treatment?

const pattern =String.raw`([a-zA-Z0-9-._~%!$&'()*+,;[email protected]]+(/[a-zA-Z0-9-._~%!$&'()*+,;=:@]+)*/?|(/[a-zA-Z0-9-._~%!$&'()*+,;=:@]+)+/?)(?[a-zA-Z0-9-._~%!$&'()*+,;=:@/?]*)?(#[a-zA-Z0-9-._~%!$&'()*+,;=:@/?]*)?`;
let re = new RegExp(pattern);
return re.test(somestring)

I also tried enclose the regex with / and / like below and it does not work either. It allows spaces but I don’t really allow space.

const re = new RegExp(/([a-zA-Z0-9-._~%!$&'()*+,;[email protected]]+(/[a-zA-Z0-9-._~%!$&'()*+,;=:@]+)*/?|(/[a-zA-Z0-9-._~%!$&'()*+,;=:@]+)+/?)(?[a-zA-Z0-9-._~%!$&'()*+,;=:@/?]*)?(#[a-zA-Z0-9-._~%!$&'()*+,;=:@/?]*)?/);

Updates: I guess my question should be how do I make sure it matches full text like what I can do test in the website above(attached screenshot below) enter image description here


I think the root of this question is that regexr is matching on the full string rather than just a part. .test() will return true if part of the regex matches. if you want to only return true when matching the on the full string I would suggest using start ^ and end $ delimiters.

const pattern =String.raw`^([a-zA-Z0-9-._~%!$&'()*+,;[email protected]]+(/[a-zA-Z0-9-._~%!$&'()*+,;=:@]+)*/?|(/[a-zA-Z0-9-._~%!$&'()*+,;=:@]+)+/?)(?[a-zA-Z0-9-._~%!$&'()*+,;=:@/?]*)?(#[a-zA-Z0-9-._~%!$&'()*+,;=:@/?]*)?$`;
let re = new RegExp(pattern);