how to match object-like pattern in a string

I have a string that looks like this:

var str='[{"id":"abcd","pin":5},{"id":"efgh","pin":6}]';

How can i match the object-like pattern in the string. I want to retrieve {"id":"abcd","pin":"5"}

I have tried this:

str.match( new RegExp('{"id":"abcd".*}'))

unfortunately, it matches till the end of the string which is not what i desire.
I just want to retrieve
{"id":"abcd","pin":"5"} by using regexp

>Solution :

If you do not wish to parse the JSON, you can use the following regular expression, but keep in mind that this only works for non-nested objects.

const str = '[{"id":"abcd","pin":5},{"id":"efgh","pin":6}]';

const [found] = str.match(/\{"id":"abcd"[^\}]*\}/);

if (found) {
  console.log(found); // {"id":"abcd","pin":5}

If you want to make this a bit more dynamic, you can try the following:

const str = '[{"id":"abcd","pin":5},{"id":"efgh","pin":6}]';

const findById = (jsonArrStr, id) =>
  str.match(new RegExp(`\\{"id":"${id}"[^\\}]*\\}`))?.pop();

console.log(findById(str, 'abcd')); // {"id":"abcd","pin":5}
console.log(findById(str, 'efgh')); // {"id":"efgh","pin":6}

If you need to retrieve the object, parse it, find it, and reserialize it.

const findBy = (jsonArrStr, predicate) =>

const str = '[{"id":"abcd","pin":5},{"id":"efgh","pin":6}]';

const found = findBy(str, ({ id }) => id === 'abcd');

console.log(found); // {"id":"abcd","pin":5}

Leave a Reply