Skip to content
Advertisement

How do you create a regex to find and replace all jsdoc array syntax from [] to Array? [closed]

I need to covert all my jsdoc array syntax from [] to Array. I using Sublime Text trying to create a find and replace regex to handle the following cases:

/**
  * @param {[]}
  * @param {[]|null}
  * @param {null|[]}
  * @param {[someType]}
  * @param {someType|[someType]}
**/

So here is what the output should be:

/**
  * @param {Array}
  * @param {Array|null}
  * @param {null|Array}
  * @param {Array.<someType>}
  * @param {someType|Array.<someType>}
**/

The regex shouldn’t interfere with js, for example:

const thing1 = [something];
const thing2 = [];
const thing3 = {thang: []};
const thing4 = {thang: [something]};

Advertisement

Answer

You can use a RegEx replace for this, for example in Visual Studio Code.

You’ll have to look at both cases separately, one case where it’s just [] and one where it’s [someType]. You can then reference the capture groups from your regular expression in your replace to retain custom content.

  1. The pattern for the [] case would be along the lines of @param(.*?)[] and the replace something like @param$1Array
  2. The pattern for the [someType] part would be along the lines of @param(.*?)[(.*?)] with the replace being @param$1Array.$2

I’ve tested this successfully for the example you provided, but try it on a spare file first. Generally, the process is always the same: Select all you need in a capture group, then replace the matches in a way that retains the existing content and applies your updates.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement