1

I'm getting the string in this format

var text = '{"STATUS_NEW":"12345678","STATUS_OLD":"87654321","TEXT":"blahblah"}';

to parse this string, i'm use this code:

var pattern = /"STATUS_NEW":"12345678"/;
var exists = pattern.test(text);
if(exists){console.log('ok');}

All work fine! console get me "ok". But I need to paste my var into 'pattern'. I tried this:

var status = '12345678'; var pattern = /"STATUS_NEW":"/ + status + /"/; //not work!

I tried to set 'status' without quotes, and it doesn't work.

rocambille
  • 15,398
  • 12
  • 50
  • 68

2 Answers2

0

You could use RegExp with a string, which you concatinate.

var text = '{"STATUS_NEW":"12345678","STATUS_OLD":"87654321","TEXT":"blahblah"}',
    status = '12345678',
    pattern = new RegExp('"STATUS_NEW":"' + status + '"'),
    exists = pattern.test(text);

if (exists){
    console.log('ok');
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

According to https://stackoverflow.com/a/185529/3711952 you have to do something like:

var pattern = new RegExp("some regex segment" + /*comment here */
              segment_part + /* that was defined just now */
              "another segment");

So in your case it will be:

var status = '12345678'; 
var pattern = new RegExp(/"STATUS_NEW":"/ + status + /"/);
Community
  • 1
  • 1