Sunday, 12 August, 2018 UTC


URLs can be tricky to work with because they can be more complicated than the traditional URL format you type in.  I was again reminded of this when I was parsing Webpack URLs when I saw this beauty:
I parsed the URL with new URL("....") but saw that the pathname included every leading slash:

Since I wanted to display a sane pathname, I wanted to figure out how to remove/replace repeated characters with JavaScript.  It was actually easier than I thought it would be:
const prettyPath = urlObj.pathname.replace(/\/{2,}/g, "/");

// > /../rbd/pnpm-volume/144384a5-85d9-4142-b9b9-168eea22eb97/node_modules/
The {2,} part of the regular expression only allows for one of the repeated characters, and /g ensures that multiple instances within the string will have the repeat character removed.
Just when I thought I’d seen it all this Webpack URL surprised me.  Luckily a small regex let me show a pretty URL in page to the user!
The post Replace Repeated Characters with JavaScript appeared first on David Walsh Blog.