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
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • By
    Get Slick with MooTools Kwicks

    When I first saw MooTools graphical navigation, I was impressed. I thought it was a very simple yet creative way of using Flash. When I right-clicked and saw that it was JavaScript, I was floored. How could they achieve such...

  • By
    Translate Content with the Google Translate API and JavaScript

    Note:  For this tutorial, I'm using version1 of the Google Translate API.  A newer REST-based version is available. In an ideal world, all websites would have a feature that allowed the user to translate a website into their native language (or even more ideally, translation would be...

Discussion

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