1

I have a regular expression like this and it works fine using https://regexr.com/

([a-zA-Z0-9-.~%!$&'()*+,;=@]+(/[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\-._~%!$&'()*+,;=@]+(\/[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\-._~%!$&'()*+,;=@]+(\/[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

4
  • 3
    What string does it work with in regexr but not in code? Commented Apr 29, 2021 at 0:20
  • Like if I have ``` or space in code, it treat it as valid but not in website above Commented Apr 29, 2021 at 1:19
  • Ok, Can you include some sample successful/failed input strings in the question? Commented Apr 29, 2021 at 1:51
  • If we can't easily reproduce the issue, it's unlikely to get answers. Commented Apr 29, 2021 at 1:51

2 Answers 2

2

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\-._~%!$&'()*+,;=@]+(\/[a-zA-Z0-9\-._~%!$&'()*+,;=:@]+)*\/?|(\/[a-zA-Z0-9\-._~%!$&'()*+,;=:@]+)+\/?)(\?[a-zA-Z0-9\-._~%!$&'()*+,;=:@/?]*)?(\#[a-zA-Z0-9\-._~%!$&'()*+,;=:@/?]*)?$`;
let re = new RegExp(pattern);
console.log(re.test('asdf```'))

Sign up to request clarification or add additional context in comments.

Comments

1

Match the beginning ^ and end $ of a string to get an exact match, otherwise a substring will be accepted.

const re = new RegExp('^regex$')

On the sample string:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.