Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Substitutions with regex for different characters?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading