My regEx doesn't work in my code

Hi there,

I’m building a regex to match the string of a website such as https://google.com

I’m doing something very basic here and my regex is the following:

/(https?://)www.\w+.com/

In https://regexr.com it matches the https://google.com string but in my code I do:

let URLvalidator = new RegExp('^(https?:\/\/)www.\w+.com$');

  console.log(URLvalidator.test('https://www.google.com'))
  console.log(URLvalidator.test("http://www.google.com"))

Both return false and I’m not getting why… I’m sure I’m missing something very obvious here. :sweat_smile:

Try adding the following right below the first line:

console.log(URLvalidator);

Does the pattern printed in the console look exactly like you want it to?

1 Like

Actually no… it prints /(https?://)www.w+.com/
So it basically takes the backward slash out before the “w+”…

Okay I got it to work now, I needed to prepend the “\w+” with another "" so the working regEx looks like:

let URLvalidator = new RegExp('(https?:\/\/)www.\\w+.com');