Replace Repeated Characters with JavaScript

By  on  

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:

webpack-internal:///../rbd/pnpm-volume/144384a5-85d9-4142-b9b9-168eea22eb97/node_modules/.registry.npmjs.org/fbjs/0.8.17/node_modules/fbjs/lib/isNode.js

I parsed the URL with new URL("....") but saw that the pathname included every leading slash:

///../rbd/pnpm-volume/144384a5-85d9-4142-b9b9-168eea22eb97/node_modules/.registry.npmjs.org/fbjs/0.8.17/node_modules/fbjs/lib/isNode.js


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/.registry.npmjs.org/fbjs/0.8.17/node_modules/fbjs/lib/isNode.js

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!

Recent Features

  • By
    CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

  • By
    Welcome to My New Office

    My first professional web development was at a small print shop where I sat in a windowless cubical all day. I suffered that boxed in environment for almost five years before I was able to find a remote job where I worked from home. The first...

Incredible Demos

  • By
    Chris Coyier’s Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it's damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...

  • By
    Web Notifications API

    Every UI framework has the same set of widgets which have become almost essential to modern sites: modals, tooltips, button varieties, and notifications.  One problem I find is each site having their own widget colors, styles, and more -- users don't get a consistent experience.  Apparently the...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!