Konstantin Mokhov Konstantin Mokhov - 1 month ago 5
jQuery Question

find text in string with variable

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);

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.


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){