Skip to content

Instantly share code, notes, and snippets.

@leonlaser
Last active January 4, 2024 15:27
Show Gist options
  • Save leonlaser/0f80006ffb66a20941ddffa16f30463a to your computer and use it in GitHub Desktop.
Save leonlaser/0f80006ffb66a20941ddffa16f30463a to your computer and use it in GitHub Desktop.
Regular expression to migration Angular Material form inputs from `placeholder` attribute to `<mat-label>` tags

Manual Angular Material/CDK placeholder migration

Why?

The removed "legacy" appearance promoted input placeholders to the floating label if the label was not specified. All newer appearance settings require explicitly specifying a if one was not provided before. This change addresses an accessibility best practice of not using labels and placeholders interchangeably.

Migrating to MDC-based Angular Material Components | Form Fields

How?

This regular expression works with IntelliJ IDE and maybe with others, supporting regex search and replace.

Search

(?s)(\s+)(<[a-z-]+[^>]*?)\s+placeholder=\"([^"]*)\"

Replace

$1<mat-label>$3</mat-label>$1$2 
  1. (?s) - makes the dot match all characters, including line breaks
  2. (\s+) - group to fetch whitespace to correctly indent code
  3. (<mat-[^>]*?) - non greedy search group until ... \s+placeholder= ...we find the placeholder and possbile whitespace to replace the whole placeholder attribute
  4. ([^"]*) - the actual content of our our new <mat-label>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment