-1

Hi I have two typescript snippet . both wants to achieve the same . however console.log prints different value. any idea what is wrong? why the code 2 prints false .

var regex1 = new RegExp(/^FEDEX /)
var messagePrefix = "FEDEX "
console.log(regex1.test(messagePrefix)); // this prints true 

let messageControlValue:string = "FEDEX "
let regex2:RegExp = new RegExp(/^messageControlValue/);
console.log(regex2.test(messagePrefix)); // this prints false

really appreciatiate any help thanks

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
knowledgeseeker
  • 339
  • 4
  • 14
  • 1
    Because `messageControlValue` in `new RegExp(/^messageControlValue/)` is a `messageControlValue` string, not a `messageControlValue` variable. You meant to use `new RegExp("^" + messageControlValue)` – Wiktor Stribiżew Jul 31 '19 at 13:39

1 Answers1

3

Because in the second one you're literally testing for the string messageControlValue. Construct it like so:

let regex2: RegExp = new RegExp(`^${messageControlValue}`);

Or:

let regex2: RegExp = new RegExp("^" + messageControlValue);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79