Skip to content

Instantly share code, notes, and snippets.

@leonlaser
Last active December 24, 2024 21:41
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>
@msmallest
Copy link

msmallest commented Dec 24, 2024

@JWess that works very nice, it helped me do tons of replacements. Thank you.

I have just two caveats for that command though, for people who may find this page:

  1. Make sure to not run it on the input for a mat-chip-row, since those work differently and this script can mess those up if done without verfying.
  2. The formatting does leave some large gaps in the first line of some input metadata like classes and whatnot, but proper style formatters should fix that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment