Home > Enterprise >  Substitutions with regex for different characters?
Substitutions with regex for different characters?

Time:10-25

I'm generating strings that will be used for the filenames of downloadable assets. The naming conventions of the assets in questions occasionally include forward slashes (/). I'm struggling to figure out how to match and replace in the following way:

  • If a whitespace is matched, replace it with an underscore (_)
  • If a forward slash is matched, replace that with something or remove it – still debating on what I would replace it with for legibility. Removing it might not make sense since I would still end up with double underscores.

I currently have this:

const chartDescriptionFormatted = chartDescriptionRaw.replace(/\s /g, '_')

Given the string Victims / Involved Parties I'm getting back this: Victims_/_Involved_Parties which is human-readable enough, but is not playing nice when I go to download the file. When the file is downloaded, the / character seen in the output is replaced with an underscore _, so my file names are ending up with a triple-underscore, like so: A screenshot of a download, showing triple underscore characters in the string generated by the above methods.

Edit: I realized that removing the / character would still, in cases like the given example, leave me with a double underscore. I'm most interested in figuring out how to match different things and replace selectively based on what was matched.

CodePudding user response:

Simplest way is to just call .replace() twice in sequence:

const chartDescriptionFormatted = chartDescriptionRaw.replace(/\//g, '')
                                                     .replace(/\s /g, '_');

First pass you remove all forward slashes. Second pass you convert any sequence of spaces into a single _. The order matters in this case. You have to first remove the forward slashes.

See demo below:

const chartDescriptionRaw = 'Victims / Involved Parties';
const chartDescriptionFormatted = chartDescriptionRaw.replace(/\//g, '')
                                                     .replace(/\s /g, '_');
                                                         
console.log(chartDescriptionRaw, '-->', chartDescriptionFormatted)

  • Related