用JavaScript替换重复字符

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:

使用URL可能会比较棘手,因为它们可能比您键入的传统URL格式更复杂。当我解析Webpack URL时,再一次想到了这一点:


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:

我用new URL("....")解析了URL,但发现pathname包含每个前导斜杠:


///../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:

由于我想显示一个合理的路径名,因此我想弄清楚如何使用JavaScript删除/替换重复的字符。 实际上,这比我想象的要容易:


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.

正则表达式的{2,}部分仅允许重复字符之一,并且/g确保字符串中的多个实例将删除重复字符。

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!

就在我以为看到了所有这些Webpack URL时,我感到惊讶。 幸运的是,一个小的正则表达式让我在页面上向用户显示了一个漂亮的URL!

翻译自: https://davidwalsh.name/replace-repeated-characters

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值