skip to Main Content

I’m using a regex that validates for an URL. The regex is:

^(https?|ftp)://[^\s/$.?#].[^\s]*$

The issue that I’m getting is that when I check for the validation in regex101. My test cases are getting validated but in my JS code it’s not validating the strings having an "s" in them.

https://regex101.com/r/Vy0MU0/1

This is the regex and the test cases that are working fine here but not working in my JS code.
I think the issue that I’m facing might be that the "S" characters are being treated as space.

let DestinationRegex = new RegExp('^(https?|ftp)://[^s/$.?#][^s$]*$');
if (DestinationRegex.test("https://atlas.mapmyindia.com")) {
     console.log("Yeahhhhhhh")
} else {
     console.log("Nahhhhlh")
} 

I tried this and always get into the else statement whenever I use the string with a S in it.

2

Answers


  1. Use the same regex directly in the if statement, it works.

    Edit: saved regex in a variable instead of using it directly, for readability.

    let DestinationRegex = /^(https?|ftp)://[^s/$.?#][^s$]*$/;
    if (DestinationRegex.test("https://atlas.mapmyindia.com")) {
      console.log("Yeahhhhhhh")
    } else {
      console.log("Nahhhhlh")
    } 
    Login or Signup to reply.
  2. Try this way, with conctructor it’s a different syntax

    let DestinationRegex= new RegExp(`(https?|ftp)://[^s/$.?#][^s$]`);
    const str= "https://atlas.mapmyindia.com";
    console.log(DestinationRegex.test("https://atlas.mapmyindia.com"))
    if (DestinationRegex.test("https://atlas.mapmyindia.com")) {
      console.log("Yeahhhhhhh");
    } else {
      console.log("Nahhhhlh");
    }
    

    Doc:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search