Search code examples
javascriptreactjsregexpattern-matchingstring-matching

Regex to Extract Props + Values from String that contains a React Component


I have a React component, but the raw string:

<MyComponent id={123} value={345} name="Thomas" />

How can I regex through this string and extract all props & their value?

{
  id: 123,
  value: 345,
  name: "Thomas"
}

I am struggling to understand how to go about something like this.

I've tried things like this, but they aren't really getting me anywhere... :

let res = myComp.match(/.*<MyComponent id={.*/g)
let value = res[0].split('{')[1].split('}')[0]

Solution

  • One option might be using a pattern with an infinite lookbehind assertion if supported and 3 capture groups with an alternation.

    Assuming there are no other occurrences of < and > in the string:

    (?<=<MyComponent\s[^<>]*)([^\s=]+)=(?:{([^{}]*)}|"([^"]*)")(?=[^<>]*\/>)
    

    See a regex101 demo;

    const regex = /(?<=<MyComponent\s[^<>]*)([^\s=]+)=(?:{([^{}]*)}|"([^"]*)")(?=[^<>]*\/>)/g;
    const s = `<MyComponent id={123} value={345} name="Thomas" />`;
    const result = {};
    Array.from(s.matchAll(regex), m => {
      result[m[1]] = m[2] ? parseInt(m[2]) : m[3]
    });
    console.log(result);