6

I'm doing an audit in a large codebase, and I need to search to find all uses of a component where it is used with a given prop. I'm thinking a regex could be useful here, but I can't figure out how to handle potential newlines in the markup. I need to be able to differentiate between these two usages, finding the latter:

<Component
  prop1="value1"
  prop2={2}
/>
<Component
  prop1="value1"
  targetProp={3}
  prop2={2}
/>

I don't care about the value of the target prop, just that it exists on the component.

dangerismycat
  • 696
  • 2
  • 13
  • 17

2 Answers2

13

<Component(\s|\n)[^>]*?property

This one support line break.

Sarawut Positwinyu
  • 4,734
  • 13
  • 50
  • 77
  • Agreed, your solution is better! Thanks! – dangerismycat Mar 12 '20 at 20:09
  • What if my component looks like this: `} property={1} />` - the regex fails because of the inner ``! Can you create a regex to support that as well? :) – Ziarno Aug 11 '20 at 09:43
  • The given solution unfortunately breaks if it meets a `>` in another Component's property: arrow functions {}} property={1} /> and components as props } property={1} /> Does anyone know if it's possible to enhance the RegExp to keep track of those? – buondevid Nov 05 '21 at 17:27
1

Here's a regex that should work:

<Component\s[^>]*?targetProp={[^>]*?\/>

This matches:

  • <Component literally, with a \s whitespace character to avoid capturing <ComponentWithALongerName
  • [^>] any character that's not >, zero or more times, lazily
  • targetProp={ literally (adjust if needed for boolean/string values)
  • [^>] any character that's not >, zero or more times, lazily
  • \/> literally
dangerismycat
  • 696
  • 2
  • 13
  • 17