Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) =>
  JSON.stringify(JSON.parse(jsonArrStr).find(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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading