Home > OS >  Regex to Extract Props Values from String that contains a React Component
Regex to Extract Props Values from String that contains a React Component

Time:12-19

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]

CodePudding user response:

The following regexp should scan all of the name/value pairs. You can use this in a matchAll() to return an iterable object with all the matches. The name is in capture group 1 and the value can be gotten by concatenating groups 3, 4, and 5. You can add javascript code to iterate this structure and build your result string.

/([\w.:-] )(\s*=\s*)(?:\{(. ?)\}|(".*?")(?<!\\")|(\w ))/gs

enter image description here

I added a little defensive check to handle escaped double-quotes inside double-quoted strings.

CodePudding user response:

Given your string, another regex that would retrieve your values is the following:

(\b\S \b)=[{"](\b\S \b)["}]

Regex Explanation:

  • (\b\S \b): Group 1, non-space characters sequence
  • =: =
  • [{"]: either open brace or double quotes
  • (\b\S \b): Group 2, , non-space characters sequence
  • [}"]: either closed brace or double quotes

Check the demo here.

let text = "<MyComponent id={123} value={345} name=\"Thomas\" />";

let regex = /(\b\S \b)=[{"](\b\S \b)["}]/g;

let results = text.matchAll(regex);

for (result of results) {
  console.log("Key:", result[1], ' Value:', result[2])
}

  • Related