Use Regex to replace old once() implementations with new one

September 6, 2023
Search replace regex

Drupal 10 doesn't have drupal/jquery.once library anymore.

It was removed to remove dependency on jQuery and was replaced with drupal/once library.

Here's the change record for it.

This results in 2 manual changes developers need to do in their custom code.

First is to replace drupal/jquery.once with drupal/once in all libraries.yml files. i.e. from:

  dependencies:
    - core/jquery.once

to:

  dependencies:
    - core/once

 

And the second one is to replace the js code where once is used. An example of this is to replace the following code:

$('.selector', context).once('identifier').click();

to

$(once('identifier', '.selector', context)).click();

 

This should be pretty simple until you realize that your project has around 100 implementations of once()

So I came up with a regex replace pattern for this.

Search for all instances of \$\((.*)\)\.once\(('.*')\) and replace them with $(once($2, $1))

To know how this works, read about REGEX patterns. Especially the concept of capture groups.