Skip to content

Instantly share code, notes, and snippets.

@ruzz311
Last active January 10, 2025 10:25
Show Gist options
  • Save ruzz311/073ae57c471a97b6cefa1a39db5d3a69 to your computer and use it in GitHub Desktop.
Save ruzz311/073ae57c471a97b6cefa1a39db5d3a69 to your computer and use it in GitHub Desktop.
Regex example to remove spaces between tags (html, xml, etc.)
// For regex testing https://regex101.com/r/dOjkeJ/2
let myStr = `<something>
<xml-like>
<example><p>with lots of spaces</p></example>
and \n characters
<xml-like>
</something>`;
// spaces:
myStr.replace(new RegExp('\>[ ]+\<', 'g'), '><');
// matches "\n" "\t" and " " (space)
myStr.replace(new RegExp('\>[\s]+\<', 'g'), '><');
@cybertrapped
Copy link

cybertrapped commented Jun 23, 2023

This one worked for me:
myStr.replace(new RegExp('>[ ]+<', 'g'), '><');

This one did not worked for me:
myStr.replace(new RegExp('>[\s]+<', 'g'), '><');

Right now, the one that works for \r,\n,\t is with double backward slashes as in:
content.replace(/\t|\r|\n|./g,"");

Thank you

@SparK-Cruz
Copy link

SparK-Cruz commented Jan 10, 2025

Why are you so weird using strings to declare regexes (which require double escaping)?
myStr.replace(/>\s+</g, '><');

@ruzz311
Copy link
Author

ruzz311 commented Jan 10, 2025

Bro, I don't even remember writing this. It's some snippet from 2017

@SparK-Cruz
Copy link

Well, almost 8 years later and it put me on track to make something work so, thank you

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