1

I get true for the below

function myFunction1() {
  var text = "hello world";
  var regex = /hello/;
  var result = regex.test(text);
  console.log((result));
}

enter image description here

Why am I getting false for this?

function myFunction() {
  var array = ["2023", "2022", "2020"];
  var regex = new RegExp("^20\d{2}$");

  for (var i = 0; i < array.length; i++) {
    var result = regex.test(array[i]);
    console.log(typeof(array[i]),result);
  }
}

The output is false for all the items in the array

I also tried changing the regex pattern as 20\d{2} but still getting false

enter image description here

Should the result not be true?

TheMaster
  • 45,448
  • 6
  • 62
  • 85
Alicia Stone
  • 432
  • 11

1 Answers1

1

In your script, how about the following modification?

From:

var regex = new RegExp("^20\d{2}$");
  • In this case, it is /^20d{2}$/. I think that this is the reason of your issue.

To:

var regex = new RegExp("^20\\d{2}$");
  • If you want to use ^20\d{2}$, please modify as follows.

    • From

        var result = regex.test(array[i]);
      
    • To

        var result = /^20\d{2}$/.test(array[i]);
      

Testing:

var array = ["2023", "2022", "2020"];
var regex = new RegExp("^20\\d{2}$");

for (var i = 0; i < array.length; i++) {
  var result = regex.test(array[i]);
  console.log(typeof(array[i]),result);
}

or,

var array = ["2023", "2022", "2020"];

for (var i = 0; i < array.length; i++) {
  var result = /^20\d{2}$/.test(array[i]);
  console.log(typeof(array[i]),result);
}

Reference:

Tanaike
  • 181,128
  • 11
  • 97
  • 165