1

I want to match the URL host part with a regular express in JavaScript. Suppose I have a URL

var str = 'www.demo-site.com:1234'    

and I designed below regular expression to match it

var regex = /^www\.demo-site\.com(:\d+)$/gi    

As I expected, regex.test(str) returns true. However, if I run it again, it returns false. Why the results from running exactly the same function twice are different?

regex.test(str); //returns true
regex.test(str); //returns false

Shuping
  • 5,388
  • 6
  • 43
  • 66

1 Answers1

7

That's because the search starts from the previous match for each invocation of test:

test called multiple times on the same global regular expression instance will advance past the previous match.

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

twaddington
  • 11,607
  • 5
  • 35
  • 46