Regular expression in javascript how to find content between two “special” characters?

I have the following line of text, I need to look for the content inside $$ and extract values for id= and description=.

Could you point me out in the right direction, I tried few times with no success (actually I tried this one ^$$(.*?)$$)

$$id=uniq_id&description=some_description$$ Any text after
// result should be: ['uniq_id', 'some_description', 'Any text after']

$$id=uniq_id$$ Any text after
// result should be: ['uniq_id', '', 'Any text after']

Any text after
// result should be: ['','','Any text after']

Answer

You use 1 capturing group (.*?) to capture between $$ and $$.

If the id should be there and the description is optional, you could use 3 capturing groups where the part that matches description is optional`:

^$$id=(w+)(?:&description=(w+))?$$(.*)

Regex demo

const regex = /^$$id=(w+)(?:&description=(w+))?$$(.*)/;
const strings = [
  "$$id=uniq_id&description=some_description$$ Any text after",
  "$$id=uniq_id$$ Any text after"
];

strings.forEach((s) => {
  console.log(s.match(regex));
});

Leave a Reply

Your email address will not be published. Required fields are marked *